from logging import Logger
from mw_helper import convert_to_dict, ensure_list
from production.box import ProductionBox
from production.box._OrderChangerProductionBox import OrderChangerProductionBox
from production.model import ProductionOrder
from typing import Optional, List, Union


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

        super(OrderPropertiesFilterBox, self).__init__(name, sons, logger)
        self.order_property = order_property
        self.allowed_values = convert_to_dict(ensure_list(allowed_values))
        self.excluded_values = convert_to_dict(ensure_list(excluded_values))
        self.remove_order = remove_order

    def change_order(
            self,
            order   # type: ProductionOrder
    ):
        # type: (...) -> Optional[ProductionOrder]

        if len(self.excluded_values) > 0 and str(getattr(order, self.order_property)) in self.excluded_values:
            if self.remove_order:
                return None
            else:
                order.items = []

        if len(self.allowed_values) > 0 and str(getattr(order, self.order_property)) not in self.allowed_values:
            if self.remove_order:
                return None
            else:
                order.items = []

        return order
