# coding: utf-8
from .const import (
    USER,
    SESSION_ID,
    __version__,
    CWD
)
import sys
import logging
from colorlog import LevelFormatter, TTYColoredFormatter


def make_formatter():
    if sys.stdout.isatty():
        return TTYColoredFormatter('%(log_color)s%(message)s',
                                   reset=True,
                                   log_colors={
                                       'DEBUG': '',
                                       'INFO': '',
                                       'WARNING': 'yellow',
                                       'ERROR': 'red',
                                       'CRITICAL': 'red,bg_white'})
    else:
        return LevelFormatter(fmt={
                              "DEBUG": "%(message)s",
                              "INFO": "%(message)s",
                              "WARNING": "!!(yellow)%(message)s!!",
                              "ERROR": "!!(red)%(message)s!!",
                              "CRITICAL": "??%(message)s??"},
                              reset=False)


def make_logger(is_debug):
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)

    if is_debug:
        file_fmt = '{} - %(asctime)s - {} - {} - %(name)s:{} - %(levelname)s - %(message)s'.format(
            SESSION_ID,
            USER,
            CWD,
            __version__
        )
        f_handler = logging.FileHandler('ta-report.log')
        f_handler.setLevel(logging.DEBUG)
        f_handler.setFormatter(logging.Formatter(file_fmt))
        logger.addHandler(f_handler)

    c_handler = logging.StreamHandler(sys.stdout)
    c_handler.setLevel(logging.INFO)
    c_handler.setFormatter(make_formatter())
    logger.addHandler(c_handler)
