from model import BaseThread
from cfgtools import Group
from datetime import datetime
from time import sleep

from rupture_events import RuptureEventTypes
from rupture_service import RuptureService


class CleanRuptureThread(BaseThread):
    def __init__(
        self,
        configs,            # type: Group
        rupture_service,    # type: RuptureService
    ):
        # type: (...) -> None

        super(CleanRuptureThread, self).__init__()

        self._start = configs.find_value("Rupture.CleanRuptureTimeWindow.StartTime", None)
        self._end = configs.find_value("Rupture.CleanRuptureTimeWindow.EndTime", None)
        self._interval = int(configs.find_value("Rupture.CleanRuptureTimeWindow.Interval", "30"))
        self.rupture_service = rupture_service

    def run(self):
        while self.running:
            sleep_time = self._interval

            try:
                now = datetime.now().time().isoformat()
                business_period = datetime.today().strftime("%Y%m%d")
                should_run = self._start and self._end and self._start <= now <= self._end

                if should_run:
                    self.rupture_service.set_last_clean_event(period=business_period)
                    self.rupture_service.clean_rupture_items(RuptureEventTypes.CleanRuptureThread)
            finally:
                sleep(sleep_time)
