import logging
import sys
from logging import Logger
import time

from rich.console import Console


class LogUtil(object):
    def __init__(self, logger: Logger, quiet: bool = False):
        self._logger = logger
        self._quiet = quiet
        self._console = Console(file=sys.stderr)

    def print_and_log(self, msg: str, level=logging.INFO, **kwargs):
        """Prints msg to console (if `quiet` param is False) and logs msg to main log file."""
        if not self._quiet:
            self._console.print(msg, **kwargs)
        self._logger.log(level, msg)

    def timer(self, name: str, log_level: int = logging.DEBUG):
        return C42Timer(self, name, log_level)


class C42Timer(object):
    def __init__(self, log_util: LogUtil, name: str, log_level: int = logging.DEBUG):
        self._log_util = log_util
        self._name = name
        self._log_level = log_level

    def __enter__(self):
        self.start = time.time()

    def __exit__(self, exc_type, exc_value, traceback):
        self.stop = time.time()
        self._log_util.print_and_log('{0} took {1:.2f} seconds'.format(self._name, (self.stop - self.start)), self._log_level)
