from logging import Logger

from mw_helper import (
    ensure_list,
    convert_to_dict,
)

from production.repository import ProductRepository
from typing import List, Optional, Union

from ._OrderChangerProductionBox import OrderChangerProductionBox
from ._ProductionBox import ProductionBox
from ..model import (
    ProductionOrder,
    Item,
)


class NoJitAddTagBox(OrderChangerProductionBox):

    def __init__(self, name, sons, product_repository, tag, logger=None):
        # type: (str, Optional[Union[List[ProductionBox], ProductionBox]], ProductRepository, List[str], Logger) -> None

        self.part_codes = convert_to_dict(ensure_list(product_repository.get_no_jit_part_codes()))
        self.tag = tag
        super(NoJitAddTagBox, self).__init__(name, sons, logger)

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

        for item in order.items:
            self.add_tag_on_item(item=item)

        return order

    def add_tag_on_item(
        self,   # type: NoJitAddTagBox
        item,   # type: Item
    ):
        # type: (...) -> None

        all_sons_tagged = True
        for son in item.items:
            if not self.add_tag_on_item(item=son):
                all_sons_tagged = False

        item_has_no_jit = item.part_code in self.part_codes and item.does_not_have_tag(tag=self.tag)
        if item_has_no_jit and (not item.is_combo() or all_sons_tagged):
            item.add_tag(tag=self.tag)
