import logging
import os
from logging.handlers import RotatingFileHandler

from scripts.config import app_configuration

_log_file_name__ = str(app_configuration.LOG_FILE_NAME)
__log_path__ = str(app_configuration.LOG_PATH)
__log_level__ = str(app_configuration.LOG_LEVEL)
__handler_type__ = str(app_configuration.LOG_HANDLER)
__max_bytes__ = int(app_configuration.LOG_MAX_BYTES)
__backup_count__ = int(app_configuration.LOG_BACKUP_COUNT)
complete_log_path = os.path.join(__log_path__, _log_file_name__)
if not os.path.isdir(__log_path__):
    os.makedirs(__log_path__)

logging.trace = logging.DEBUG - 5
logging.addLevelName(logging.DEBUG - 5, 'TRACE')


class ILensLogger(logging.getLoggerClass()):
    def __init__(self, name):
        super().__init__(name)

    def trace(self, msg, *args, **kwargs):
        if self.isEnabledFor(logging.trace):
            self._log(logging.trace, msg, args, **kwargs)


def get_logger(log_file_name=complete_log_path, log_level=__log_level__, time_format="%Y-%m-%d %H:%M:%S",
               handler_type=__handler_type__, max_bytes=__max_bytes__, backup_count=__backup_count__):
    """
     Creates a rotating log
     """
    log_file = os.path.join(log_file_name + '.log')
    logging.setLoggerClass(ILensLogger)
    __logger__ = logging.getLogger(log_file_name)
    __logger__.setLevel(log_level.strip().upper())
    debug_formatter = '%(asctime)s - %(levelname)-6s - %(name)s - [%(threadName)5s:%(filename)5s:' \
                      '%(funcName)5s():''%(lineno)s] - %(message)s'
    formatter_string = '%(asctime)s - %(levelname)-6s - %(name)s - %(levelname)3s - %(message)s'

    if log_level.strip().upper() == log_level:
        formatter_string = debug_formatter

    formatter = logging.Formatter(formatter_string, time_format)

    # if str(handler_type).lower() == "console_handler":
    # Console Handler
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    if __logger__.hasHandlers():
        __logger__.handlers.clear()
    # __logger__.addHandler(console_handler)

    if str(handler_type).lower() == "rotating_file_handler":
        # Rotating File Handler
        handler = RotatingFileHandler(log_file, maxBytes=max_bytes, backupCount=backup_count)
        handler.setFormatter(formatter)
        if __logger__.hasHandlers():
            __logger__.handlers.clear()
        __logger__.addHandler(handler)

    else:
        # File Handler
        hdlr_service = logging.FileHandler(log_file)
        hdlr_service.setFormatter(formatter)
        if __logger__.hasHandlers():
            __logger__.handlers.clear()
        __logger__.addHandler(hdlr_service)

    return __logger__


logger = get_logger()
