import re

from logging import Logger
from typing import (
    List,
    Optional,
    Union,
)

from mw_helper import ensure_list, convert_to_dict

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

JIT_SEPARATOR = "[|\-><$]"


class NonValidJitAddTagBox(OrderChangerProductionBox):
    def __init__(
        self,               # type: NonValidJitAddTagBox
        name,               # type: str
        sons,               # type: Union[str, List[str]]
        tag,                # type: str
        valid_jits,         # type: List[str]
        logger=None,        # type: Optional[Logger]
    ):
        # type: (...) -> None

        super(NonValidJitAddTagBox, self).__init__(name, sons, logger)

        self.valid_jits = convert_to_dict(ensure_list(valid_jits))
        self.tag = tag

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

        for item in order.items:
            self.add_tag_on_invalid_jits(item)

        return order

    def add_tag_on_invalid_jits(
        self,       # type: NonValidJitAddTagBox
        item,       # type: Item
    ):
        # type: (...) -> None

        item_jits = re.split(JIT_SEPARATOR, item.jit_lines)
        invalid_jits = [x for x in item_jits if x and x not in self.valid_jits]
        if invalid_jits:
            item.add_tag(tag=self.tag, line_jit_list=invalid_jits)

        for son in item.items:
            self.add_tag_on_invalid_jits(son)
