import json

from application.interactor.unlock_voucher import UnlockVoucherInteractor
from application.interactor.unlock_voucher.dto import UnlockVoucherRequest
from application.model import AsyncUuidMessageProcessor
from messagebus import (
    DefaultToken,
    Message,
    InternalErrorMessage,
)


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

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

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

        request_json = json.loads(data.decode("utf-8"))
        return UnlockVoucherRequest(
            benefit_id=request_json["benefitId"],
            order_picture=request_json["orderPicture"],
            table_picture=request_json.get("tablePicture")
        )

    def call_business(
        self,           # type: UnlockVoucherProcessor
        request,        # type: UnlockVoucherRequest
    ):
        # type: (...) -> None

        self.interactor.unlock_benefit(
            request=request,
        )

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

    def format_exception(self, message_bus, message, event, input_obj, exception):
        message_bus.reply_message(
            message=message,
            reply_message=InternalErrorMessage(ex=exception)
        )

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