import json
import logging

from datetime import datetime
from sysactions import get_model, get_custom, clear_custom

from application.repository import ServicePeriodRepository
from actions import mb_context
from typing import List, Tuple, Union


class ServicePeriodInteractor(object):
    def __init__(self):
        # type: () -> None

        self.logger = logging.getLogger("PosActions")
        self.service_period = ServicePeriodRepository(mb_context)

    def get_services_period(self):
        # type: () -> List

        try:
            result = []
            current_time = datetime.now().time()
            services = self.service_period.get_services_period()
            day_of_week = str(datetime.now().weekday() + 1)
            for service in services:
                start = datetime.strptime(service["startHour"], "%H:%M:%S").time()
                end = datetime.strptime(service["endHour"], "%H:%M:%S").time()
                week_day = service["weekDays"].split(",")
                service["isValid"] = start <= current_time <= end and day_of_week in week_day
                result.append(service)

            if len(result) > 0:
                result = sorted(result, key=lambda k: (k['isValid'] < True, k['name']))

            return result
        except Exception as _:
            self.logger.exception("Error getting service period")
            return []

    def verify_if_service_periods_exist(self, pos_list):
        # type: (Tuple)-> None

        if len(pos_list) == 0:
            return

        all_service_period_id = self._get_service_periods_id()
        for pos_id in pos_list:
            try:
                if len(all_service_period_id) == 0:
                    clear_custom(pos_id, 'SERVICE_PERIOD', True)
                    continue

                current_service_period = json.loads(self._get_pos_current_service_period(int(pos_id)))
                current_service_id = current_service_period.get("servicePeriodId")
                if current_service_id is not None and current_service_id not in all_service_period_id:
                    clear_custom(pos_id, 'SERVICE_PERIOD', True)

            except Exception as _:
                self.logger.exception('Error clear service period pos controller POS: {}'.format(pos_id))

    @staticmethod
    def _get_pos_current_service_period(pos_id):
        # type: (int)-> Union[unicode, str]

        model = get_model(pos_id)
        special_catalog = get_custom(model, 'SERVICE_PERIOD')
        if special_catalog in ['', None]:
            return '{}'

        return special_catalog

    def _get_service_periods_id(self):
        # type: ()-> [int]

        services = self.get_services_period()
        return [int(service["id"]) for service in services] if len(services) > 0 else []
