import logging
import contextlib


logger = logging.getLogger("mirror")
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter(fmt="%(message)s"))
logger.addHandler(handler)


__level = logging.INFO
__prefix = []


def set_log_level(level):
    global __level
    if isinstance(level, bool):
        level = logging.DEBUG if level else logging.INFO
    elif isinstance(level, str):
        n_level = getattr(logging, level.upper(), None)
        if not isinstance(n_level, int):
            raise RuntimeError("Invalid log level: %s" % level)
        level = n_level
    elif not isinstance(level, int):
        raise RuntimeError("Invalid log level: %s" % level)
    __level = level
    logger.setLevel(level)
    handler.setLevel(level)


def is_verbose():
    global __level
    return __level <= logging.DEBUG


def set_log_prefix():
    global __prefix
    global handler
    fmt = "".join(__prefix + ["%(message)s"])
    handler.setFormatter(logging.Formatter(fmt=fmt))


def push_log_prefix(pfx):
    global __prefix
    n_prefix = len(__prefix)
    __prefix.append(pfx)
    set_log_prefix()
    return n_prefix


def pop_log_prefix(count=None):
    global __prefix
    if count is None:
        count = len(__prefix) - 1
    del __prefix[count:]
    set_log_prefix()


@contextlib.contextmanager
def log_prefix(pfx):
    n_prefix = push_log_prefix(pfx)
    try:
        yield
    finally:
        pop_log_prefix(n_prefix)
