import json
from xml.etree import cElementTree as eTree

from typing import Optional

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, event_type):
        # type: (str, str) -> int

        data = json.loads(data)
        pos_id = int(data.get("pos_id"))

        return pos_id

    def call_business(self, pos_id):
        # type: (int) -> Optional[eTree.XML]

        return self.interactor.execute(pos_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)))
