from ctypes import Union
from logging import Logger

from mw_helper import ensure_list
from typing import (
    List,
    Optional,
)

from ._ItemFilterBox import ItemFilterBox
from ..repository import ProductRepository


class ItemCustomParamsFilterBox(ItemFilterBox):

    def __init__(
        self,                   # type: ItemCustomParamsFilterBox
        name,                   # type: str
        sons,                   # type: Union[str, List[str]]
        product_repository,     # type: ProductRepository
        custom_params,          # type: List[str]
        inherit_comments,       # type: bool
        logger=None,            # type: Optional[Logger]
    ):
        # type: (...) -> None

        allowed_part_codes = self._get_allowed_values(
            product_repository=product_repository,
            custom_params=custom_params,
        )

        super(ItemCustomParamsFilterBox, self).__init__(
            name=name,
            sons=sons,
            allowed_part_codes=allowed_part_codes,
            forbidden_part_codes=[],
            inherit_comments=inherit_comments,
            logger=logger
        )

    @staticmethod
    def _get_allowed_values(
        product_repository,     # type: ProductRepository
        custom_params,          # type: List[str]
    ):
        # type: (...) -> List[int]

        allowed_part_codes = []
        custom_params_list = ensure_list(custom_params)
        products_with_custom_params = product_repository.get_products_with_custom_params(ensure_list(custom_params))
        for custom_param in custom_params_list:
            if custom_param in products_with_custom_params:
                allowed_part_codes.extend(products_with_custom_params.get(custom_param).keys())

        return allowed_part_codes
