import json
from xml.etree import cElementTree as eTree

from typing import (
    Optional,
    Tuple,
)

from application.service import OrderService

from application.interactor import OnOrderReopenInteractor
from application.model import Configurations
from messagebus import DefaultToken, DataType, Message
from messageprocessorutil import UuidMessageProcessor


class OnOrderReopenProcessor(UuidMessageProcessor):
    def __init__(self, configs, interactor, order_service):
        # type: (Configurations, OnOrderReopenInteractor, OrderService) -> None

        super(OnOrderReopenProcessor, self).__init__()
        self.logger = configs.logger
        self.configs = configs
        self.interactor = interactor
        self.order_service = order_service

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

        data = json.loads(data)
        pos_id = int(data.get("pos_id"))
        table_id = data.get("table_id") or None

        return pos_id, table_id

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

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

    def format_response(self, message_bus, message, event, request, response):
        if message:
            data = eTree.tostring(element=response) if response is not None else ""
            message_bus.reply_message(
                message=message,
                reply_message=Message(
                    token=DefaultToken.TK_SYS_ACK,
                    data_type=DataType.string,
                    data=data,
                ),
            )

    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)))
