# -*- coding: utf-8 -*-
import base64
import json

from model import (
    PaymentResponseData,
    StartPaymentData,
    FinishPaymentData,
)
from paymentrouter import PaymentError

from ._CommonProcessor import _CommonProcessor


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

    def call_business(self, obj):
        # type: (StartPaymentData) -> str
        try:
            processor = self.payment_router.get_payment_processor(obj.electronic_type)
            add_payment_response = processor.add_payment(obj)

            if obj.tender_id and hasattr(add_payment_response, 'id_auth'):
                self.payment_router.finish_all_payments(
                    FinishPaymentData(
                        pos_id=obj.pos_id,
                        order_id=obj.order_id,
                        fiscal_date=obj.fiscal_date,
                        fiscal_time=obj.fiscal_time,
                        status="1",
                        tender_details=json.dumps(base64.b64encode(self.get_tender_details(add_payment_response))),
                        tender_id=obj.tender_id,
                    )
                )

            return add_payment_response.to_xml()
        except PaymentError:
            self.payment_router.logger.warning("Error in Start Payment Processor", exec_info=True)

    @staticmethod
    def get_tender_details(
        payment_data  # type: PaymentResponseData
    ):
        # type: (...) -> str

        tender_details = json.dumps({
            "Media": payment_data.media.strip(),
            "CNPJAuth": payment_data.cnpj_auth,
            "TransactionProcessor": payment_data.transaction_processor,
            "Bandeira": payment_data.bandeira,
            "IdAuth": payment_data.id_auth,
            "AuthCode": payment_data.auth_code,
            "ReceiptCustomer": payment_data.receipt_customer,
            "ReceiptMerchant": payment_data.receipt_merchant,
            "AccreditorSat": payment_data.sat_acquirer if hasattr(payment_data, 'sat_acquirer') else None,
            "tBand": payment_data.t_band if hasattr(payment_data, 't_band') else None,
            "tPag": payment_data.t_pag if hasattr(payment_data, 't_pag') else None,
            "NsuHost": payment_data.nsu_host if hasattr(payment_data, 'nsu_host') else None,
            "CardNumber": payment_data.card_number if hasattr(payment_data, 'card_number') else None,
            "TransactionIdentifier": payment_data.transaction_identifier,
        })

        return tender_details
