import asyncio
import threading
import signal
import time
from rotation_handler import HandleRotation


class BgRotation:

    def __init__(self, configs):

        self.stop_loop = asyncio.Event()

        self.configs = configs
        self.interval = self.configs["log_rotation_configs"].get(
            "check_interval", 90)
        self._rotation_handler = HandleRotation(self.configs)

        self.signals = [signal.SIGINT, signal.SIGTERM]
        self.create_signal()

        self.task = threading.Thread(target=self.run_task, daemon=True)
        self.task.start()

    def run_task(self):
        asyncio.run(self.bg_rotation_check(self.interval))

    def bg_rotation_check(self, interval):

        while not self.stop_loop.is_set():
            self._rotation_handler.rotate_log_path()

            time.sleep(interval)

    def break_task(self, signum, frame):
        self.stop_loop.set()

    def create_signal(self):

        for signal_type in self.signals:
            signal.signal(signal_type, self.break_task)
