from typing import (
    List,
    Optional,
    Union,
)

from mw_helper import ensure_iterable

from production.model import ProductionOrder
from ._OrderChangerProductionBox import OrderChangerProductionBox


class CustomPropertyValueFilterBox(OrderChangerProductionBox):
    def __init__(
        self,                       # type: CustomPropertyValueFilterBox
        name,                       # type: str
        sons,                       # type: Union[str, List[str]]
        parameter_name,             # type: str
        allowed_values=None,        # type: Optional[List[str]]
        excluded_values=None,       # type: Optional[List[str]]
        remove_order=True,          # type: Optional[bool]
        logger=None
    ):
        # type (...) -> None

        super(CustomPropertyValueFilterBox, self).__init__(name, sons, logger)

        self.parameter_name = parameter_name
        self.allowed_values = [x.lower() for x in ensure_iterable(allowed_values or [])]
        self.excluded_values = [x.lower() for x in ensure_iterable(excluded_values or [])]
        self.remove_order = remove_order

    def change_order(
        self,       # type: CustomPropertyValueFilterBox
        order,      # type: ProductionOrder
    ):
        # type (...) -> ProductionOrder

        if self.should_filter_order(order):
            if self.remove_order:
                return None

            order.items = []

        return order

    def should_filter_order(
        self,       # type: CustomPropertyValueFilterBox
        order,      # type: ProductionOrder
    ):
        # type: (ProductionOrder) -> bool

        if self.parameter_name in order.properties:
            prop_value = order.properties[self.parameter_name].lower()
            if self.allowed_values and prop_value not in self.allowed_values:
                return True

            if self.excluded_values and prop_value in self.excluded_values:
                return True

        return False
