from logging import Logger
from typing import (
    Dict,
    Optional,
    List,
)

from production.model import (
    BuilderNotFoundException,
    ProdStates,
)
from production.box.unsplitter import StoredOrderUnsplitter
from production.treebuilder import BoxConfiguration
from ._BoxBuilder import BoxBuilder


class OrderUnsplitterBoxBuilder(BoxBuilder):

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

        super(OrderUnsplitterBoxBuilder, self).__init__(loggers)

    def build(
        self,      # type: OrderUnsplitterBoxBuilder
        config,    # type: BoxConfiguration
    ):
        # type: (...) -> StoredOrderUnsplitter

        splitter_box = self._get_splitter_box(config=config)
        if splitter_box is None:
            raise BuilderNotFoundException()

        return splitter_box

    def _get_splitter_box(
        self,      # type: OrderUnsplitterBoxBuilder
        config,    # type: BoxConfiguration
    ):
        # type: (...) -> Optional[StoredOrderUnsplitter]

        split_type = config.extra_config.get("SplitType")
        prod_states_clean_cache = self._get_prod_states_clean_cache(config=config)
        if split_type is None:
            return None

        split_type = split_type.upper()
        if split_type in "STORED":
            return StoredOrderUnsplitter(
                name=config.name,
                sons=config.sons,
                prod_states_clean_cache=prod_states_clean_cache,
            )

        return None

    @staticmethod
    def _get_prod_states_clean_cache(
        config,    # type: BoxConfiguration
    ):
        # type: (...) -> List[str]

        default_prod_states = [ProdStates.SERVED, ProdStates.INVALID]
        return config.extra_config.get("ProdStatesToCleanCache", default_prod_states)
