import json
import time

from messagebus import Event
from model import PaymentResponseMessage
from paymentprocessor import PaymentProcessor
from msgbus import MBException


class MobileSitefPaymentProcessor(PaymentProcessor):
    def connection_status(self, test_connection_data):
        return True

    def add_payment(self, start_payment_data):
        return PaymentResponseMessage("Mobile Sitef cannot process transactions")

    def cancel_payment(self):
        pass  # Mobile Sitef doesn't handle cancel non-finished transactions

    def finish_payment(self, finish_payment_data):
        pos_id = finish_payment_data.pos_id
        order_id = finish_payment_data.order_id
        status = finish_payment_data.status
        fiscal_date = finish_payment_data.fiscal_date
        fiscal_time = finish_payment_data.fiscal_time
        transaction_data = {
            "timeStamp": time.time(),
            "confirmTransaction": status,
            "transactionIdentifier": str(pos_id) + str(order_id),
            "fiscalDate": fiscal_date,
            "fiscalTime": fiscal_time
        }

        data = json.dumps(transaction_data)
        retry = 0
        while retry < 3:
            try:
                event_xml = """<Event subject="POS{}" type="MOBILE">
                                   <MOBILE_CONFIRM_TRANSACTION>
                                       {}
                                   </MOBILE_CONFIRM_TRANSACTION>
                               </Event>""".format(pos_id, data)

                self.message_bus.publish_event(Event("POS{}".format(int(pos_id)), "MOBILE", event_xml))
            except MBException:
                self.logger.exception("Error sending mobile confirm transaction")
            finally:
                retry += 1

    def get_name(self):
        return "MobileSitef"
