from sys import stdout
from loguru import logger
from logging import getLogger
from common.api.core.ApiLogHandler import ApiLogHandler
from common.lib.enums.TermFilesPath import TermFilesPath
from common.lib.data_models.Config import Config
from common.lib.constants import LogDefinition


class Logger:
    rotation = f"{LogDefinition.LOG_MAX_SIZE_MEGABYTES} MB"
    format = LogDefinition.LOGFILE_DATE_FORMAT
    compression = LogDefinition.COMPRESSION
    _config: Config

    @property
    def config(self):
        return self._config

    @config.setter
    def config(self, config):
        self._config = config

    def __init__(self, config: Config):
        self.config = config
        self.setup()

    def setup(self):
        self.remove()
        self.add_file_handler()

    @staticmethod
    def remove():
        logger.remove()

    def add_api_handler(self):
        handler = ApiLogHandler()

        for name in ("uvicorn", "uvicorn.error", "uvicorn.access"):
            log = getLogger(name)
            log.handlers = [handler]
            log.propagate = False
            log.setLevel(self.config.debug.level)

    def add_file_handler(self, filename=TermFilesPath.LOG_FILE_NAME):
        logger.add(
            filename,
            format=self.format,
            level=self.config.debug.level,
            rotation=self.rotation,
            compression=self.compression,
            backtrace=False,
            diagnose=False,
            retention=self.config.debug.backup_storage_depth if self.config.debug.backup_storage_depth_exists else 0,
        )

    def add_stdout_handler(self):
        logger.add(
            stdout,
            format=self.format,
            level=self.config.debug.level,
            backtrace=False,
            diagnose=False,
        )

    def add_wireless_handler(self, wireless_handler) -> int:
        handler_id = logger.add(
            wireless_handler,
            format=LogDefinition.DISPLAY_DATE_FORMAT,
            level=self.config.debug.level,
            backtrace=False,
            diagnose=False,
        )

        return handler_id
