# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2016 Continuum Analytics, Inc.
#
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
# -----------------------------------------------------------------------------
"""Logger utilties."""

# Standard library imports
import logging.handlers
import os

# Local imports
from anaconda_navigator.config import LOG_FILENAME, LOG_FOLDER

logfile = os.path.join(LOG_FOLDER, LOG_FILENAME)


def setup():
    """Setup, create and return a logger."""
    if not os.path.isdir(LOG_FOLDER):
        os.mkdir(LOG_FOLDER)

    logger = logging.getLogger('navigator')
    logger.setLevel(logging.DEBUG)

    max_log_size = 2 * 1024 * 1024
    ch = logging.handlers.RotatingFileHandler(logfile, maxBytes=max_log_size,
                                              backupCount=5, mode='w')
    ch.setLevel(logging.DEBUG)

    f = ('%(asctime)s - %(levelname)s\n'
         '    %(module)s.%(funcName)s : %(lineno)d\n'
         '    %(message)s\n')

    formatter = logging.Formatter(f)
    ch.setFormatter(formatter)

    logger.addHandler(ch)

    logger.info('Setting up logger')
    return logger


logger = setup()


def logme(func):
    """
    Can use this as a decorator to log all calls to some function.

    If used with the standard formatter above, the function name and location
    will always be right here (not very useful).
    """
    def f(*args, **kwargs):
        logger.debug(" ".join([str(func), str(args), str(kwargs)])[:40])
        func(*args, **kwargs)
    return f
