from logging import Logger
from typing import Optional

from production.box._OrderChangerProductionBox import OrderChangerProductionBox


class CFHHiderBox(OrderChangerProductionBox):
    def __init__(
        self,
        name,               # type: str
        sons,               # type: object
        cfh_items,          # type: object
        inherit_comments,   # type: bool
        logger=None,        # type: Optional[Logger]
    ):
        # type: (...) -> None

        super(CFHHiderBox, self).__init__(name, sons, logger)
        self.cfh_items = cfh_items
        self.inherit_comments = inherit_comments

    def change_order(self, order):
        order.items = self._find_and_remove_cfh_items(order.items[:])
        return order

    def _find_and_remove_cfh_items(self, items):
        new_items = []
        for item in items:
            if item.part_code in self.cfh_items:
                for son in item.items:
                    son.handle_remove_father(
                        father=item,
                        inherit_comments=self.inherit_comments,
                    )
                    new_items.extend(self._find_and_remove_cfh_items([son]))
            else:
                for son in item.items:
                    if self.inherit_comments and son.part_code in self.cfh_items:
                        son.repeat_comment_from_father(father=item)
                item.items = self._find_and_remove_cfh_items(item.items)
                new_items.append(item)

        return new_items
