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

__all__ = ['DispatchingFormatter', 'WidgetHandler', 'Handlers', 'HANDLERS', 'logger']

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

# Cell
from .config import CONFIG, APP_DIR
from .widgets import Textarea

# Cell
class DispatchingFormatter:
    """Dispatch formatter for logger and it's sub logger."""
    def __init__(self):
        self.formatters = {
            '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
class WidgetHandler(Textarea, logging.Handler):

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

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

# Cell
class Handlers():

    def __init__(self, level, filename, mode):
        self.formatter = DispatchingFormatter()
        self.handlers = {}
        self.level = getattr(logging, level)
        self.logger = self.getLogger(__name__)

        ''' capture warnings '''
        logging.captureWarnings(True)
        self.py_warnings_logger = logging.getLogger('py.warnings')

        ''' add file handler '''
        self.addHandler('file', logging.FileHandler(filename, mode))
        self.logger.info('logging.captureWarnings(True)')


        ''' need to be loaded '''
        self.loaded = False
        self.requireBaseUrl = None

    def addHandler(self, name, handler):
        handler.setFormatter(self.formatter)
        self.py_warnings_logger.addHandler(handler)
        self.handlers[name] = handler
        self.logger = self.getLogger(__name__)

    def addWidget(self, widget):
        self.addHandler('widget', widget)

    def loadCSS(self):
        css_path = os.path.join(APP_DIR, 'assets/css')
        self.logger.info('Loading css files...')
        for file in list(Path(css_path).rglob('*.css')):
            with open(file, 'r') as f:
                try:
                    filestr = '<style>\n' + f.read() + '\n</style>'
                    display(HTML(filestr))
                    self.logger.info('\t%s' % file)
                except:
                    self.logger.exception('Error loading css file %s' % file)

    def _ipython_display_(self):
        if 'widget' in self.handlers:
            display(self.handlers['widget'])
            if not self.loaded:
                self.loadCSS()

    def getLogger(self, name='__main__'):
        logger = logging.getLogger(name)
        logger.setLevel(self.level)
        for handler in self.handlers.values():
            logger.addHandler(handler)
        return logger

# Cell
HANDLERS = Handlers(CONFIG['LOG']['level'], CONFIG['LOG']['filename'], CONFIG['LOG']['mode'])
HANDLERS.addWidget(WidgetHandler())
logger = HANDLERS.getLogger(__name__)
logger.info('Welcome to Superpower!')