import logging
import logging.handlers
import datetime


class TerminalColors:
    PURPLE = HEADER = '\033[95m'
    BLUE = OKBLUE = '\033[94m'
    GREEN = OKGREEN = '\033[92m'
    YELLOW = WARNING = '\033[93m'
    RED = FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


def color_string(string: str, color: str) -> str:
    return '{color}{s}{end}'.format(color=color, s=string, end=TerminalColors.ENDC)


def get_logger(name=None):
    root_logger_name = 'hawk-soard'

    # Build the name of the sub-logger
    if name:
        name = root_logger_name + '.' + name
    else:
        name = root_logger_name

    root_logger = logging.getLogger(root_logger_name)
    # if root_logger:
    #    return root_logger
    # If the root logger has no handlers, add them
    # in any case return the sub-logger
    if root_logger.handlers:
        return logging.getLogger(name)
    else:
        hdlr = logging.handlers.WatchedFileHandler("./hawk-soard.log")
        # hdlr = logging.handlers.WatchedFileHandler("/var/log/hawk/hawk-soard.log")
        myAlt = AltFormatter()
        hdlr.setFormatter(myAlt)
        root_logger.addHandler(hdlr)
        root_logger.setLevel(logging.DEBUG)  # todo: make it configurable

        return logging.getLogger(name)


class AltFormatter(logging.Formatter):

    def __init__(self, msgfmt=None, datefmt=None):
        logging.Formatter.__init__(self, None, "%H:%M:%S")

    def format(self, record):
        self.converter = datetime.datetime.fromtimestamp
        ct = self.converter(record.created)
        asctime = ct.strftime("%Y-%m-%d %H:%M:%S")
        msg = record.getMessage()
        name = record.name
        if (record.levelno == logging.CRITICAL) or (record.levelno == logging.ERROR):
            record.levelname = "[E]"
        if (record.levelno == logging.WARNING):
            record.levelname = "[W]"
        if (record.levelno == logging.INFO):
            record.levelname = "[I]"
        if (record.levelno == logging.DEBUG):
            record.levelname = "[D]"
        return '%(timestamp)s: %(levelname)s %(message)s' % {'timestamp': asctime, 'levelname': record.levelname, 'message': msg}
