from model import EftData, PaymentResponseMessage
from paymentprocessor import PaymentProcessor
from ._SitefProcessor import stop_sitef_processor, get_sitef_processor

from sysdefs import eft


class SitefMercadoPagoPaymentProcessor(PaymentProcessor):
    def __init__(self, message_bus, dialog_manager, config, logger):
        super(SitefMercadoPagoPaymentProcessor, self).__init__(message_bus, dialog_manager, config, logger)
        self.sitef_processor = get_sitef_processor(message_bus, dialog_manager, config, logger)
        self.show_qr_code = config.find_value("ShowQRCode", "false").lower() == "true"
        self.allowed_payments = config.find_values("AllowedPayments") or []
        self.forbidden_payments = config.find_values("ForbiddenPayments") or []
        self.additional_data = self._get_additional_data()

    def connection_status(self, test_connection_data):
        return self.sitef_processor.connection_status(test_connection_data)

    def _get_additional_data(self):
        additional_data_list = []
        if self.show_qr_code:
            additional_data_list.append("{DevolveStringQRCode=1}")
        if self.allowed_payments:
            additional_data_list.append("{{CarteirasDigitaisHabilitadas={}}}".format(';'.join(self.allowed_payments)))
        if self.forbidden_payments:
            additional_data_list.append("{{RestricoesCarteirasDigitais={}}}".format(';'.join(self.forbidden_payments)))
        return ';'.join(additional_data_list)

    def add_payment(self, start_payment_data):
        start_payment_data.tender_type = 122
        ret = self.sitef_processor.add_payment(start_payment_data, 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(self):
        return self.sitef_processor.cancel_payment()

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

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

    def stop(self):
        stop_sitef_processor()
