import sys
import logging


logger = None


def get_logger(reset=False, stream=sys.stdout, formatted=False) -> logging.Logger:
    """
    Returns logger for p4utils-for-unreal operations. Creates
    a new logger if one does not already exist for the app.

    :param reset: Remove all stream handlers and replaces them with a new one
    :param stream: Logger stream receiving handler logs
    :return logging.Logger:
    """
    global logger
    if logger is None:
        logger = logging.getLogger('p4utils-for-unreal')
        logger.setLevel(logging.DEBUG)
        add_handler(stream, formatted)

    if reset:
        reset_stream(stream, formatted)

    return logger

def reset_stream(stream, formatted):
    """
    Resets logger stream. May be used to prevent inactive 
    sys.stdout stream issue when DCC closes.
    """
    global logger

    while logger.handlers:
        handler = logger.handlers[0]
        handler.close
        logger.removeHandler(handler)

    logger.setLevel(logging.DEBUG)
    add_handler(stream, formatted)

def get_formatter():
    return logging.Formatter(
                fmt='[{asctime}][{levelno}] {name}: {message}',
                datefmt='%m/%d/%Y %H:%M:%S',
                style='{'
            )

def add_handler(stream, formatted):
    global logger
    sh = logging.StreamHandler(stream)
    if formatted:
        sh.setFormatter(get_formatter())
    logger.addHandler(sh)