import base64
import json

from constants import PAPER_PART_CUT
from msgbus import TK_PRN_PRINT, FM_PARAM
from sysactions import get_storewide_config, get_model, get_current_order, get_used_service, show_confirmation, \
    get_podtype


class PrintReceipt(object):
    def __init__(self, mb_context, logger):
        self.mb_context = mb_context
        self.logger = logger

        merchant_config = "Store.PrintMerchantReceipt"
        self.print_merchant_receipt = get_storewide_config(merchant_config, defval="False").lower() == "true"
        ask_customer_config = "Store.AskPrintCustomerReceipt"
        self.ask_print_customer_receipt = get_storewide_config(ask_customer_config, defval="True").lower() == "true"
        customer_config = "Store.PrintCustomerReceipt"
        self.print_customer_receipt = get_storewide_config(customer_config, defval="False").lower() == "true"

    def print_tef_receipts(self, pos_id):
        try:
            model = get_model(pos_id)
            tenders = get_current_order(model).findall("TenderHistory/Tender")
            electronic_tenders = []
            for tender in tenders:
                if int(tender.get("eletronicType")) not in (0, 9):
                    electronic_tenders.append(tender)

            if len(electronic_tenders) == 0:
                return

            current_printer = get_used_service(model, "printer")

            pod_type = get_podtype(model)
            if self.print_merchant_receipt and pod_type != "TT":
                self._print_receipt(current_printer, electronic_tenders, "ReceiptMerchant")

            if self._has_customer_receipt(electronic_tenders):
                if self.ask_print_customer_receipt:
                    response = show_confirmation(pos_id, "$WANT_TO_PRINT_CUSTOMER_RECEIPT")
                    if response:
                        self._print_receipt(current_printer, electronic_tenders, "ReceiptCustomer")
                elif self.print_customer_receipt:
                    self._print_receipt(current_printer, electronic_tenders, "ReceiptCustomer")

        except Exception as _:
            self.logger.exception("Error printing TEF receipts")

    def _print_receipt(self, current_printer, electronic_tenders, receipt_type):
        for tender in electronic_tenders:
            receipt_data = json.loads(tender.get("tenderDetail"))[receipt_type]
            if receipt_data != "":
                receipt = base64.b64decode(receipt_data)
                receipt += PAPER_PART_CUT
                self.mb_context.MB_EasySendMessage(current_printer, TK_PRN_PRINT, FM_PARAM, receipt, 30000000)

    def _has_customer_receipt(self, electronic_tenders):
        for tender in electronic_tenders:
            receipt_data = json.loads(tender.get("tenderDetail"))["ReceiptCustomer"]
            if receipt_data != "":
                return True
        return False
