import logging


class _CustomFormatter(logging.Formatter):
    grey = "\x1b[38;20m"
    yellow = "\x1b[33;20m"
    red = "\x1b[31;20m"
    bold_red = "\x1b[31;1m"
    reset = "\x1b[0m"
    fmt = "%(asctime)s - [%(levelname)s] -%(module)s- %(message)s"

    FORMATS = {
        logging.DEBUG: grey + fmt + reset,
        logging.INFO: grey + fmt + reset,
        logging.WARNING: yellow + fmt + reset,
        logging.ERROR: red + fmt + reset,
        logging.CRITICAL: bold_red + fmt + reset
    }

    old_factory = logging.getLogRecordFactory()

    def _record_factory(*args, **kwargs):
        record = _CustomFormatter.old_factory(*args, **kwargs)
        _module = record.module
        _levelname = record.levelname
        if len(_module) % 2 == 0 and len(_module) < 12:
            _module = ' ' * ((12 - len(_module)) // 2) + _module + ' ' * ((12 - len(_module)) // 2)
        elif len(_module) % 2 == 1 and len(_module) < 12:
            _module = ' ' * ((12 - len(_module)) // 2) + record.module + ' ' * ((12 - len(_module)) // 2 + 1)
        if len(_levelname) % 2 == 0 and len(_levelname) < 8:
            _levelname = ' ' * ((8 - len(_levelname)) // 2) + _levelname + ' ' * ((8 - len(_levelname)) // 2)
        elif len(record.levelname) % 2 == 1 and len(record.module) < 8:
            _levelname = ' ' * ((8 - len(_levelname)) // 2) + _levelname + ' ' * ((8 - len(_levelname)) // 2 + 1)
        record.module = _module
        record.levelname = _levelname
        return record

    logging.setLogRecordFactory(_record_factory)

    def format(self, record):
        log_fmt = self.FORMATS.get(record.levelno)
        formatter = logging.Formatter(log_fmt, "%d-%m-%Y %H:%M:%S")
        return formatter.format(record)


logger = logging.getLogger('Pisya_Bot')
logger.setLevel(logging.DEBUG)

ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(_CustomFormatter())
logger.addHandler(ch)
