import json

from messagebus import (
    AckMessage,
    DataType,
    NakMessage
)
from modelcommon.model import (
    SitefResponse,
    SitefResponseJsonEncoder
)
from typing import (
    Any,
    Union
)

from ._CommonProcessor import _CommonProcessor
from model import CancelPaymentOrderData


class CancelPaymentOrderProcessor(_CommonProcessor):
    def parse_data(
        self,
        data,       # type: str
        event_type  # type: str
    ):
        # type: (...) -> CancelPaymentOrderData

        data = json.loads(data or "{}")
        return CancelPaymentOrderData(data)

    def call_business(
        self,
        cancel_payment_order_data   # type: CancelPaymentOrderData
    ):
        # type: (...) -> Any[Union[str, SitefResponse]]

        processor = self.payment_router.get_payment_processor(cancel_payment_order_data.electronic_type)
        if processor:
            return processor.cancel_payment_order(cancel_payment_order_data=cancel_payment_order_data)

    def format_response(self, message_bus, message, event, input_obj, result):
        if isinstance(result, SitefResponse):
            result = json.dumps(result, cls=SitefResponseJsonEncoder)
            message_bus.reply_message(message, AckMessage(data=result, data_type=DataType.string))
        else:
            message_bus.reply_message(message, NakMessage(data=result, data_type=DataType.string))
