import json
from xml.etree import cElementTree as eTree

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

from typing import Optional

from application.interactor import OnSaleItemInteractor
from application.model import Configurations


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

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

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