from mw_helper import ensure_iterable

from ._OrderChangerProductionBox import OrderChangerProductionBox


class FilterOrderIfAllItemsHaveTagBox(OrderChangerProductionBox):
    def __init__(self, name, sons, tags, filter_type, logger=None):
        super(FilterOrderIfAllItemsHaveTagBox, self).__init__(name, sons, logger)
        self.tags = ensure_iterable(tags)
        self.filter_type = filter_type

    def change_order(self, order):
        allowed_line_numbers = []
        for item in order.items:
            self._check_allowed_lines(allowed_line_numbers, item)

        if self.filter_type.lower() == FilterType.by_order.lower():
            if not allowed_line_numbers:
                order.items = []

            return order

        order.items = [x for x in order.items if x.line_number in allowed_line_numbers]
        return order

    def _check_allowed_lines(self, allowed_line_numbers, item):
        if not item.displayed_jit:
            item_has_tag = any([x in self.tags for x in item.tags])
        else:
            item_has_tag = self._check_displayed_jit_has_some_tag(item, item.displayed_jit, self.tags)

        son_lines = []
        if not item.is_product():
            for son in item.items:
                self._check_allowed_lines(son_lines, son)

        if not item_has_tag or son_lines:
            allowed_line_numbers.append(item.line_number)

    @staticmethod
    def _check_displayed_jit_has_some_tag(item, necessary_jit_lines, tag_types):
        for jit in necessary_jit_lines:
            for tag_type in tag_types:
                tag_name = "{}-{}".format(tag_type, jit.lower()) if tag_type != "wait-prep-time" else tag_type
                if tag_name in item.tags:
                    return True

        return False


class FilterType(object):
    by_order = "byOrder"
    by_lines = "byLines"
