import json
from typing import (
    Optional,
    Tuple
)

from messagebus import DefaultToken, DataType, Message
from messageprocessorutil import UuidMessageProcessor

from application.interactor import OnTableOpenInteractor
from application.model import Configurations


class OnTableOpenProcessor(UuidMessageProcessor):
    def __init__(self, configs, interactor):
        # type: (Configurations, OnTableOpenInteractor) -> None
        super(OnTableOpenProcessor, self).__init__()
        self.logger = configs.logger
        self.configs = configs
        self.interactor = interactor

    def parse_data(self, data, event_type):
        # type: (str, str) -> int

        data = json.loads(data)
        pos_id = int(data.get("pos_id"))
        table_id = int(data.get("table_id"))
        return pos_id, table_id

    def call_business(
            self,
            params  # type: Tuple[int, str]
    ):
        # type: (...) -> Optional[str]

        pos_id, table_id = params
        return self.interactor.execute(pos_id, table_id)

    def format_response(self, message_bus, message, event, request, response):
        if message:
            message_bus.reply_message(message, Message(DefaultToken.TK_SYS_ACK, DataType.string, response))

    def format_exception(self, message_bus, message, event, input_obj, exception):
        if message:
            message_bus.reply_message(message, Message(DefaultToken.TK_SYS_NAK, DataType.param, str(exception)))

    def format_parse_exception(self, message_bus, message, event, data, exception):
        if message:
            message_bus.reply_message(message, Message(DefaultToken.TK_SYS_NAK, DataType.param, str(exception)))
