#  Copyright (C) 2021
#  ABM, Moscow
#
#  UNPUBLISHED PROPRIETARY MATERIAL.
#  ALL RIGHTS RESERVED.
#
#  Authors: Mike Orlov <m.orlov@abm-jsc.ru>
#
import logging
import os
from logging.handlers import RotatingFileHandler

import sys
from dataclasses import dataclass
from typing import Optional


@dataclass
class LogsConfig:
    level: str = "DEBUG"
    filename: str = None
    max_file_size_megabytes: int = 10
    max_files_amount: int = 10


class CustomFormatter(logging.Formatter):
    def __init__(self, msg=None, *args, **kwargs):
        if msg is None:
            msg = '<%(asctime)s/%(name)s:%(lineno)s/%(levelname)s>-  %(message)s'
        logging.Formatter.__init__(self, msg, *args, **kwargs)

    def format(self, record: logging.LogRecord):
        record.name = f'{os.getpid()}/{record.name.rsplit(".")[0].rsplit("/")[-1]}'
        return logging.Formatter.format(self, record)


def init_logs(settings: Optional[LogsConfig] = None, logging_formatter: Optional[logging.Formatter] = None) -> None:
    if settings is None:
        settings = LogsConfig()

    root = logging.getLogger()
    root.setLevel(settings.level)

    if settings.filename is None:
        ch = logging.StreamHandler(sys.stdout)
    else:
        max_file_bytes = settings.max_file_size_megabytes * 1024 * 1024
        ch = RotatingFileHandler(settings.filename, maxBytes=max_file_bytes, backupCount=settings.max_files_amount)
    ch.setLevel(logging.getLevelName(settings.level))

    if logging_formatter is None:
        ch.setFormatter(CustomFormatter(datefmt='%Y-%m-%d %H:%M:%S'))
    else:
        ch.setFormatter(logging_formatter)
    root.addHandler(ch)
