import base64

from messagebus import MessageBus
from sysactions import get_model

from production.model import PickListOrderNotFoundException
from production.repository import ProductionRepository
from production.service import PrinterService
from production.util import parse_constants
from typing import (
    Dict,
    Optional,
)


class PickListOrdersInteractor(object):
    def __init__(
        self,
        message_bus,                # type: MessageBus
        production_repository,      # type: ProductionRepository
    ):
        # type: (...) -> None

        self.timeout = 10000 * 1000
        self.production_repository = production_repository
        self.printer_service = PrinterService(
            message_bus=message_bus,
            timeout=self.timeout,
        )

    def execute(
        self,
        obj,    # type: Dict
    ):
        # type: (...) -> Optional[Dict]

        pos_id = obj.get("posId")
        orders_list = obj.get("ordersList")
        pick_list_order_id = obj.get("selectedOption", None)

        if pick_list_order_id is not None:
            printer_name = obj.get("printerName", None)
            self._print(
                pos_id=pos_id,
                printer_name=printer_name,
                pick_list_order_id=int(pick_list_order_id),
            )
            return {}

        return self.production_repository.get_all_pick_list_orders(
            orders_list=orders_list,
        )

    def _print(
        self,
        pos_id,                 # type: str
        printer_name,           # type: str
        pick_list_order_id,     # type: str
    ):
        # type: (...) -> None

        result = self.production_repository.get_data_pick_list_order(
            pick_list_order_id=pick_list_order_id,
        )

        if not result:
            raise PickListOrderNotFoundException()

        pick_list_to_print = base64.b64decode(result)

        pick_list_to_print = parse_constants(
            pos_id=pos_id,
            printer_text=pick_list_to_print,
            is_reprint=True,
        )

        self.printer_service.send_to_printer(
            printer_name=printer_name,
            text=pick_list_to_print,
        )
