# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/04_log.ipynb (unless otherwise specified).

__all__ = ['DispatchingFormatter', 'FORMATTER', 'ROOT_LOGGER', 'FILE_HANDLER', 'WidgetHandler', 'WIDGET_HANDLER',
           'getLogger', 'logger', 'loadCSS']

# Cell
import ipywidgets as ipyw
import traitlets
import warnings
import os, pathlib, urllib
from IPython.display import HTML, Javascript, display
from pathlib import Path
import logging
from .config import CONFIG

# Cell
class DispatchingFormatter:
    """Dispatch formatter for logger and it's sub logger."""
    def __init__(self):
        self.formatters = {
            'root': logging.Formatter('%(message)s'),
            'r.console': logging.Formatter('[R.%(levelname)s] %(message)s'),
            #'js.output': logging.Formatter('[JS.OUTPUT] %(message)s'),
            #'js': logging.Formatter('[JS.%(levelname)s] %(message)s'),
            'py.warnings': logging.Formatter('[PY.WARNINGS] %(message)s'),
            '__main__': logging.Formatter('[PY.%(levelname)s] %(message)s'),
            'default': logging.Formatter('[PY.%(levelname)s](%(name)s:%(lineno)d)  %(message)s')
        }

    def format(self, record):
        formatter = self.formatters.get(record.name, self.formatters['default'])
        return formatter.format(record)

# Cell
FORMATTER = DispatchingFormatter()

# Cell
ROOT_LOGGER = logging.getLogger('')
ROOT_LOGGER.setLevel(CONFIG['LOG']['level'])

# Cell
FILE_HANDLER = logging.FileHandler(CONFIG['LOG']['filename'],
                               CONFIG['LOG']['mode'])
FILE_HANDLER.setFormatter(FORMATTER)
logging.getLogger('').addHandler(FILE_HANDLER)

# Cell
class WidgetHandler(ipyw.Textarea, logging.Handler):

    def __init__(self, config):
        super().__init__(layout={'width': '100%', 'height': '250px'}, disabled=True)
        self.config = config

    def emit(self, record):
        self.value += str(self.format(record)) + '\n'

# Cell
WIDGET_HANDLER = WidgetHandler(CONFIG)
WIDGET_HANDLER.setFormatter(FORMATTER)
logging.getLogger('').addHandler(WIDGET_HANDLER)

# Cell
def getLogger(name=''):
    return logging.getLogger(name)

# Cell
logger = getLogger()
logger.info('Welcome to Superpower!')

# Cell
logging.captureWarnings(CONFIG['LOG']['captureWarnings'])

# Cell
def loadCSS():
    css_path = CONFIG.app_dir / 'assets/css'
    logger = logging.getLogger(__name__)
    logger.info('Loading css files...')
    for file in list(css_path.rglob('*.css')):
        with open(file, 'r') as f:
            try:
                filestr = '<style>\n' + f.read() + '\n</style>'
                display(HTML(filestr))
                logger.info('\t%s' % file)
            except:
                logger.exception('Error loading css file %s' % file)