# Borrowed and modified from xbmcswift
import logging

from kodi_six import xbmc

from elementum.addon import ADDON, ADDON_ID

class XBMCHandler(logging.StreamHandler):
    xbmc_levels = {
        'DEBUG': 0,
        'INFO': 2,
        'WARNING': 3,
        'ERROR': 4,
        'CRITICAL': 5,
    }

    def emit(self, record):
        xbmc_level = self.xbmc_levels.get(record.levelname)
        xbmc.log(self.format(record), xbmc_level)


loggers = {}

def _get_logger(name):
    global loggers

    if loggers.get(name):
        return loggers.get(name)
    else:
        logger = logging.getLogger(ADDON_ID)
        log_level = ADDON.getSetting("log_level")
        if log_level == 0:
            logger.setLevel(logging.CRITICAL)
        elif log_level == 1:
            logger.setLevel(logging.ERROR)
        elif log_level == 2:
            logger.setLevel(logging.INFO)
        else:
            logger.setLevel(logging.DEBUG)

        handler = XBMCHandler()
        handler.setFormatter(logging.Formatter('[%(name)s] %(message)s'))
        logger.addHandler(handler)
        return logger


log = _get_logger(__name__)
