import json

from typing import Any

from messagebus import (
    DataType,
    DefaultToken,
    Event,
    Message,
    MessageBus
)
from messageprocessorutil import UuidMessageProcessor

from application.interactor import OnTabOpenInteractor
from application.model import Configurations


class OnTabOpenProcessor(UuidMessageProcessor):
    def __init__(
            self,
            configs,    # type: Configurations
            interactor  # type: OnTabOpenInteractor
    ):
        # type: (...) -> None

        super(OnTabOpenProcessor, self).__init__()
        self.logger = configs.logger
        self.configs = configs
        self.interactor = interactor

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

        data = json.loads(data)
        pos_id = int(data.get("pos_id"))
        table_id = int(data.get("table_id")[4:])
        return pos_id, table_id

    def call_business(
            self,   # type: OnTabOpenProcessor
            params  # type: tuple
    ):
        # type: (...) -> str

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

    def format_response(
            self,           # type: OnTabOpenProcessor
            message_bus,    # type: MessageBus
            message,        # type: Message
            event,          # type: Event
            request,        # type: Any
            response        # type: Any
    ):
        # type: (...) -> None

        if message:
            message_bus.reply_message(
                message=message,
                reply_message=Message(
                    DefaultToken.TK_SYS_ACK,
                    DataType.string,
                    response
                )
            )

    def format_exception(
            self,           # type: OnTabOpenProcessor
            message_bus,    # type: MessageBus
            message,        # type: Message
            event,          # type: Event
            input_obj,      # type: Any
            exception       # type: Any
    ):
        # type: (...) -> None

        if message:
            message_bus.reply_message(
                message=message,
                reply_message=Message(
                    DefaultToken.TK_SYS_NAK,
                    DataType.param,
                    str(exception)
                )
            )

    def format_parse_exception(
            self,           # type: OnTabOpenProcessor
            message_bus,    # type: MessageBus
            message,        # type: Message
            event,          # type: Event
            data,           # type: Any
            exception       # type: Any
    ):
        # type: (...) -> None

        self.format_exception(
            message_bus=message_bus,
            message=message,
            event=event,
            input_obj=data,
            exception=exception,
        )
