from typing import Dict

from helper import json_serialize

from externals.util import BaseThread, LoggerUtil

logger = LoggerUtil.get_logger_name(__name__)


class LogManager(BaseThread):
    def __init__(self, name, counter, context="", sleep_time=60):
        # type: (str, Dict[str, int], str, int) -> None
        
        super(LogManager, self).__init__()

        self.name = name
        self.counter = counter

        self.context = context
        self.sleep_time = sleep_time

        logger.info("Creating LogManager [{}] with [{}]s of sleep time".format(self.context, sleep_time))

    def run(self):
        # type: () -> None
        
        logger.info("Starting LogManager [{}]".format(self.context))
        try:
            while self.running:
                self._print_counter(self.counter, self.name)
                self.sleep(self.sleep_time)
        except Exception as _:
            logger.exception("LogManager [{}] EXCEPTION:".format(self.context))

    def stop(self):
        # type: () -> None
    
        logger.warning("Stopping LogManager [{}]".format(self.context))

        self.running = False
        with self.sleep_condition:
            self.sleep_condition.notify()

    def _print_counter(self, d, name):
        # type: (Dict[str, int], str) -> None
        
        counted = json_serialize(d)
        total = sum(d.values())
        d.clear()
        logger.info("[{}][{}]: [{}] -> [{}]".format(self.context, name, total, counted))
