import datetime

from tornado.log import app_log

from solax_py_library.smart_scene.core.condition.base import BaseCondition
from solax_py_library.smart_scene.types.condition import (
    DateConditionItemData,
    DateConditionType,
    ConditionType,
    TimeConditionType,
)
from solax_py_library.utils.time_util import parse_time


class DateCondition(BaseCondition):
    condition_type = ConditionType.date

    def __init__(self, update_value_function, **kwargs):
        super().__init__(update_value_function, **kwargs)

    def meet_func(self, data: DateConditionItemData, ctx):
        if data.childType == DateConditionType.time:
            time_type = data.childData.data[0]
            if time_type == TimeConditionType.time:
                return self.check_time_point(data.childData.data)
            elif time_type == TimeConditionType.timeRange:
                return self.check_start_end_time(data.childData.data)
        return False

    def check_time_point(self, data):
        _, time_point = data
        hour, minute = parse_time(time_point)
        app_log.info(
            f"meet_time: {self.value.get('hour')}, {self.value.get('minute')}, data_value: {time_point}"
        )
        if hour == self.value.get("hour") and minute == self.value.get("minute"):
            return True
        return False

    def check_start_end_time(self, data):
        _, start, end = data

        start_hour, start_minute = parse_time(start)
        end_hour, end_minute = parse_time(end)

        year, month, day, hour, minute = (
            self.value.get(k) for k in ("year", "month", "day", "hour", "minute")
        )

        cur_timestamp = datetime.datetime.strptime(
            f'{year}-{month}-{day} {self.value.get("hour")}:{self.value.get("minute")}',
            "%Y-%m-%d %H:%M",
        )
        start_timestamp = datetime.datetime.strptime(
            f"{year}-{month}-{day} {start_hour}:{start_minute}", "%Y-%m-%d %H:%M"
        )
        end_timestamp = datetime.datetime.strptime(
            f"{year}-{month}-{day} {end_hour}:{end_minute}:59", "%Y-%m-%d %H:%M:%S"
        )

        if end_hour > start_hour and (
            end_hour == start_hour and end_minute > start_minute
        ):
            return True if start_timestamp <= cur_timestamp <= end_timestamp else False
        elif end_hour == start_hour and end_minute == start_minute:
            return True
        else:
            if (
                start_timestamp
                <= cur_timestamp
                <= datetime.datetime.strptime(
                    f"{year}-{month}-{day} 23:59:59", "%Y-%m-%d %H:%M:%S"
                )
            ):
                return True
            if (
                datetime.datetime.strptime(
                    f"{year}-{month}-{day} 00:00", "%Y-%m-%d %H:%M"
                )
                <= cur_timestamp
                <= end_timestamp
            ):
                return True
        return False
