"""Helper functions for dodo.py"""

from pathlib import Path
import logging
import functools


def log_to_file(output_file):
    """Decorator to log to specified file while running function."""
    def decorator_log_to_file(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            logger = logging.getLogger('')
            logger.setLevel(logging.DEBUG)
            Path(output_file).parent.mkdir(parents=True, exist_ok=True)
            fh = logging.FileHandler(output_file)
            fh.setLevel(logging.DEBUG)
            formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            fh.setFormatter(formatter)
            logger.addHandler(fh)
            logger.info("=" * 40)
            logger.info("Starting doit run")
            logger.info("=" * 40)
            result = func(*args, **kwargs)
            logger.removeHandler(fh)
            return result
        return wrapper
    return decorator_log_to_file


def setup_logging_to_console(level=logging.WARNING):
    """Log WARNING messages from all loggers to stderr."""
    console = logging.StreamHandler()
    console.setLevel(level)
    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)
