import sys
from abc import ABCMeta
from logging import Logger

from production.box.statistic import StatisticBox
from production.manager import PublishScheduler
from production.model import (
    StatisticClassNotFoundException,
    MissingBoxParameterException,
)
from production.treebuilder import BoxConfiguration
from typing import Dict

from ._BoxBuilder import BoxBuilder


class StatisticBoxBuilder(BoxBuilder):
    __metaclass__ = ABCMeta

    def __init__(
        self,  # type: StatisticBoxBuilder
        publish_scheduler,  # type: PublishScheduler
        loggers,  # type: Dict[str, Logger]
    ):
        # type: (...) -> None

        super(StatisticBoxBuilder, self).__init__(loggers)
        self.publish_scheduler = publish_scheduler

    def build(self, config):
        # type: (BoxConfiguration) -> StatisticBox

        def get_config(config_name, default=None):
            return self.get_extra(config, config_name, default)

        statistic_class_name = self.get_extra_config(config, "StatisticClass")
        statistic_type = getattr(sys.modules["production.box.statistic"], statistic_class_name, None)
        if statistic_type is None:
            raise StatisticClassNotFoundException("StatisticClass ({}) does not exist".format(statistic_class_name))

        return statistic_type(
            config.name,
            config.sons,
            self.publish_scheduler,
            self.get_logger(config),
            get_config
        )

    def get_extra_config(self, config, config_name, default=None):
        config_value = self.get_extra(config, config_name, default)
        if config_value is None:
            raise MissingBoxParameterException("({}) does not exist".format(config_name))

        return config_value
