from bustoken import TK_ELECTRONIC_PAYMENT_REFUND_CANCELED
from messagebus import (
    DataType,
    Message,
    NakMessage
)
from modelcommon.customexception import SitefFinishPaymentRefundCanceled

from ._CommonProcessor import _CommonProcessor
from model import FinishPaymentData


class FinishPaymentProcessor(_CommonProcessor):
    def parse_data(self, data, event_type):
        return FinishPaymentData(*data.split(';'))

    def call_business(self, finish_payment_data):
        # type: (FinishPaymentData) -> str
        return self.payment_router.finish_all_payments(finish_payment_data)

    def format_exception(self, message_bus, message, event, input_obj, exception):
        exception_message = self._get_message(exception=exception)
        message_bus.reply_message(message, exception_message)

    @staticmethod
    def _get_message(
        exception   # type: BaseException
    ):
        # type: (...) -> Message

        if isinstance(exception, type(SitefFinishPaymentRefundCanceled)):
            return Message(TK_ELECTRONIC_PAYMENT_REFUND_CANCELED, DataType.param, str(exception))

        return NakMessage(exception.message)
