from modelcommon.model import SitefResponse
from sysdefs import eft
from typing import (
    Any,
    Union
)

from model import (
    CancelPaymentOrderData,
    ConfirmFinishPaymentData,
    EftData,
    PaymentResponseMessage,
    TestConnectionData
)
from paymentprocessor import PaymentProcessor
from ._SitefPaymentProcessor import SitefPaymentProcessor


class SitefDebitPaymentProcessor(PaymentProcessor):
    def __init__(self, message_bus, dialog_manager, config, logger):
        super(SitefDebitPaymentProcessor, self).__init__(message_bus, dialog_manager, config, logger)
        self.sitef_processor = SitefPaymentProcessor(message_bus, dialog_manager, config, logger)
        self.allowed_payments = config.find_values("AllowedPayments") or []
        self.additional_data = self._get_additional_data()

    def connection_status(
        self,
        test_connection_data    # type: TestConnectionData
    ):
        # type: (...) -> bool

        return self.sitef_processor.connection_status(test_connection_data=test_connection_data)

    def add_payment(self, start_payment_data):
        ret = self.sitef_processor.add_payment(
            start_payment_data=start_payment_data,
            additional_params=self.additional_data,
        )
        self.register_eft_activity(EftData(start_payment_data.pos_id, start_payment_data.session_id, eft.EFT_CREDITSALE,
                                           0 if isinstance(ret, PaymentResponseMessage) else 1,
                                           start_payment_data.amount, orderid=start_payment_data.order_id))
        return ret

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

        return self.sitef_processor.cancel_payment_order(cancel_payment_order_data=cancel_payment_order_data)

    def cancel_payment(self):
        return self.sitef_processor.cancel_payment()

    def finish_payment(self, finish_payment_data):
        return self.sitef_processor.finish_payment(finish_payment_data)

    def confirm_finish_payment(
        self,
        confirm_finish_payment_data     # type: ConfirmFinishPaymentData
    ):
        # type: (...) -> None

        pass

    def _get_additional_data(self):
        additional_data_list = []
        if self.allowed_payments:
            additional_data_list.append("{{TransacoesHabilitadas={}}}".format(';'.join(self.allowed_payments)))

        return ';'.join(additional_data_list)

    def get_name(self):
        return self.sitef_processor.get_name()

    def stop(self):
        self.sitef_processor.stop()
