from production.box._OrderChangerProductionBox import OrderChangerProductionBox

from ._AllowedForbiddenFilter import AllowedForbiddenFilter


class TagFilterBox(OrderChangerProductionBox):
    def __init__(
        self,
        name,
        sons,
        allowed_tags,
        forbidden_tags,
        ignore_tags,
        allow_combos,
        keep_item_with_sons,
        keep_combos_without_sons,
        inherit_comments,
        logger=None
    ):
        super(TagFilterBox, self).__init__(name, sons, logger)
        self.filter = AllowedForbiddenFilter(
            allowed_values=allowed_tags,
            forbidden_values=forbidden_tags,
            ignore_values=ignore_tags,
            keep_son_parts=allow_combos,
            keep_item_with_sons=keep_item_with_sons,
            inherit_comments=inherit_comments,
        )

        self.keep_combos_without_sons = keep_combos_without_sons.lower() == 'true'

    def change_order(self, order):
        combo_without_sons = []
        for item in order.items:
            if item.is_combo() and not item.has_some_product_child():
                combo_without_sons.append(item.get_line_id())

        filtered_order = self.filter.filter_items(order, lambda x: x.get_tags())

        filtered_combos_order = []
        for item in filtered_order.items:
            if not item.is_combo() or self.keep_combos_without_sons:
                filtered_combos_order.append(item)
                continue

            if item.has_some_product_child() or item.get_line_id() in combo_without_sons:
                filtered_combos_order.append(item)

        filtered_order.items = filtered_combos_order
        return filtered_order
