from datetime import (
    datetime,
    time,
)
from typing import (
    Dict,
    Optional,
    Set,
    Union,
)


class ServicePeriod(object):

    def __init__(
        self,               # type: ServicePeriod
        id,                 # type: int
        name,               # type: str
        start_hour,         # type: str
        end_hour,           # type: str
        week_days,          # type: str
        automatic,          # type: bool
        price_list_id,      # type: int
        price_list_abbr,    # type: str
    ):
        # type: (...) -> None

        self.id = id
        self.name = name
        self.start_hour = start_hour
        self.end_hour = end_hour
        self.week_days = week_days
        self.automatic = automatic
        self.price_list_id = price_list_id
        self.price_list_abbr = price_list_abbr
        self.parsed_start = None   # type: Optional[time]
        self.parsed_end = None     # type: Optional[time]
        self.active_days = set()   # type: Set[str]

    def to_dict(self):
        # type: () -> Dict[str, Union[int, str]]

        return {
            "id": self.id,
            "name": self.name,
            "startHour": self.start_hour,
            "endHour": self.end_hour,
            "weekDays": self.week_days,
            "automatic": self.automatic,
            "priceListId": self.price_list_id,
            "priceListAbbr": self.price_list_abbr,
        }

    def parse_schedule(self):
        # type: () -> None

        try:
            self.parsed_start = datetime.strptime(self.start_hour, "%H:%M:%S").time()
            self.parsed_end = datetime.strptime(self.end_hour, "%H:%M:%S").time()
            self.active_days = set(self.week_days.split(","))
        except (ValueError, TypeError, AttributeError):
            self.parsed_start = None
            self.parsed_end = None
            self.active_days = set()

    def to_active_dict(self):
        # type: () -> Dict[str, Union[int, str]]

        return {
            "servicePeriodId": self.id,
            "servicePeriodName": self.name,
            "servicePeriodAbbr": self.price_list_abbr,
            "servicePeriod": "SP{}".format(self.id),
        }
