# MicroPython reimplementation of Python's logging library
#
# Copied unmodified from the micropython-lib repository
# https://github.com/micropython/micropython-lib/blob/master/logging/logging.py
#
# Original library is MIT licensed, as noted in setup.py
# https://github.com/micropython/micropython-lib/blob/master/logging/setup.py

import sys
import _thread
import utime
from src.timeutil import format_date, format_time
from src.globals import CK_DAY_NR
from src.pycom_util import mk_on_boot_fn

CRITICAL    = 50
TRACEBACK   = 45
ERROR       = 40
WARNING     = 30
INFO        = 20
DEBUG       = 10
NOTSET      = 0

_level_dict = {
    CRITICAL: "CRIT",
    TRACEBACK: "TRACEBACK",
    ERROR: "ERROR",
    WARNING: "WARN",
    INFO: "INFO",
    DEBUG: "DEBUG",
}

_stream = sys.stderr
_lock = _thread.allocate_lock()

class Logger:

    level = NOTSET

    def __init__(self, name, to_file=True):
        day_nr = mk_on_boot_fn(CK_DAY_NR, default=0)()
        self.name = name
        self.to_file = to_file
        self.path = '/flash/logs/{}.txt'.format(day_nr)
    
    def _level_str(self, level):
        l = _level_dict.get(level)
        if l is not None:
            return l
        return "LVL%s" % level

    def setLevel(self, level):
        self.level = level

    def isEnabledFor(self, level):
        return level >= (self.level or _level)

    def update_path(self):
        day_nr = mk_on_boot_fn(CK_DAY_NR, default=0)()
        self.path = '/flash/logs/{}.txt'.format(day_nr)

    def log(self, level, msg, *args):
        if level >= (self.level or _level):
            if self.to_file: f = open(self.path, 'a')
            _stream.write("%s:%s:" % (self._level_str(level), self.name))
            if self.to_file: f.write("%s:%s:" % (self._level_str(level), self.name))
            if not args:
                print(msg, file=_stream)
                if self.to_file: f.write(msg)
            else:
                print(msg % args, file=_stream)
                if self.to_file: f.write(msg % args)
            
            if self.to_file: 
                f.write('\n')
                f.close()

    def debug(self, msg, *args):
        self.log(DEBUG, msg, *args)

    def info(self, msg, *args):
        self.log(INFO, msg, *args)

    def warning(self, msg, *args):
        self.log(WARNING, msg, *args)

    def error(self, msg, *args):
        self.log(ERROR, msg, *args)

    def traceback(self, e):
        import uio as io
        from sys import print_exception
        buff = io.BytesIO()
        print_exception(e, buff)

        traceback = buff.getvalue().decode().split('\n')
        for line in traceback:
            self.log(TRACEBACK, line)

    def critical(self, msg, *args):
        self.log(CRITICAL, msg, *args)

    def exc(self, e, msg, *args):
        self.log(ERROR, msg, *args)
        sys.print_exception(e, _stream)

    def exception(self, msg, *args):
        self.exc(sys.exc_info()[1], msg, *args)


_level = INFO
_loggers = {}

def getLogger(name, to_file=True):
    if name in _loggers:
        return _loggers[name]

    l = Logger(name, to_file=to_file)
    _loggers[name] = l
    return l

def info(msg, *args):
    getLogger(None).info(msg, *args)

def debug(msg, *args):
    getLogger(None).debug(msg, *args)

def basicConfig(level=INFO, filename=None, stream=None, format=None):
    global _level, _stream
    _level = level
    if stream:
        _stream = stream
    if filename is not None:
        print("logging.basicConfig: filename arg is not supported")
    if format is not None:
        print("logging.basicConfig: format arg is not supported")
