import re

from logging import Logger

from mw_helper import ensure_iterable
from production.box import ProductionBox
from production.repository import ProductRepository
from typing import List, Optional, Union

from ._ItemFilterBox import ItemFilterBox


class JitItemFilterBox(ItemFilterBox):
    def __init__(
            self,
            name,                       # type: str
            sons,                       # type: Optional[Union[List[ProductionBox]], ProductionBox]
            repository,                 # type: ProductRepository
            allowed_jit_lines=None,     # type: Optional[Union[str, List[str]]]
            forbidden_jit_lines=None,   # type: Optional[Union[str, List[str]]]
            logger=None,                # type: Logger
    ):
        # type: (...) -> None

        self.allowed_jit_lines = ensure_iterable(allowed_jit_lines) if allowed_jit_lines is not None else None
        self.forbidden_jit_lines = ensure_iterable(forbidden_jit_lines) if forbidden_jit_lines is not None else None

        allowed_codes = None
        if allowed_jit_lines is not None:
            allowed_jit_lines = ensure_iterable(allowed_jit_lines)
            allowed_codes = repository.get_part_codes_of_jit_lines(allowed_jit_lines)

        forbidden_codes = None
        if forbidden_jit_lines is not None:
            forbidden_jit_lines = ensure_iterable(forbidden_jit_lines)
            forbidden_codes = repository.get_part_codes_of_jit_lines(forbidden_jit_lines)

        super(JitItemFilterBox, self).__init__(name, sons, allowed_codes, forbidden_codes, logger)

    def forbidden_part_code(self, item):
        if not self.forbidden_jit_lines:
            return False

        item_jit_lines = re.findall('(\\w+)', item.jit_lines)
        for jit_line in self.forbidden_jit_lines:
            if jit_line in item_jit_lines:
                return True

        return False

    def allowed_part_code(self, item):
        if not self.allowed_jit_lines:
            return True

        item_jit_lines = re.findall('(\\w+)', item.jit_lines)
        for jit_line in self.allowed_jit_lines:
            if jit_line in item_jit_lines:
                return True

        return False
