import json

from typing import Tuple

from application.interactor import BurnVoucherInteractor, UnlockVoucherInteractor
from application.model import AsyncUuidMessageProcessor
from application.model.configuration import Configurations
from messagebus import DefaultToken, DataType, Message


class UnlockVoucherProcessor(AsyncUuidMessageProcessor):
    def __init__(self, configs, interactor):
        # type: (Configurations, UnlockVoucherInteractor) -> None

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

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

        request_json = json.loads(data.decode("utf-8"))
        return str(request_json["benefitId"]), int(request_json["posId"])

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

        benefit_id = data_tuple[0]
        pos_id = data_tuple[1]

        self.interactor.unlock_benefit(
            benefit_id=benefit_id,
            pos_id=pos_id,
        )

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

    def format_exception(self, message_bus, message, event, input_obj, exception):
        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):
        message_bus.reply_message(message, Message(DefaultToken.TK_SYS_NAK, DataType.param, str(exception)))
