import json
import logging

import sysactions

from xml.etree import cElementTree as eTree
from actions.eft import (
    save_cancel_receipt,
    confirm_finish_eft_transactions,
    set_eft_cache,
)

logger = logging.getLogger("EftActions")


@sysactions.action
def confirm_cancel_eft_mobile_transactions(
    pos_id,             # type: str
    data,               # type: str
    result_code=None,   # type: str
    message=None        # type: str
):
    # type: (...) -> None

    try:
        if not data or result_code != "0":
            error = "Error confirm cancel eft mobile transactions: {} | {} | {}".format(result_code, message, data)
            logger.error(error)
            if result_code not in ["-100", "-101"]:
                error_message = message if message else "$ERROR_CANCEL_ELECTRONIC_PAYMENTS_ORDER"
                sysactions.show_messagebox(pos_id, error_message)
            return

        model = sysactions.get_model(pos_id)
        order = sysactions.get_posot(model)

        data_cancel = json.loads(data)
        transaction_identifier = str(data_cancel.get("TransactionIdentifier", ""))
        identifier_len = len(transaction_identifier)
        order_id = int(transaction_identifier[:-3]) if identifier_len > 3 else ""
        tender_id = int(transaction_identifier[-3:]) if identifier_len > 3 else ""

        order_picture = eTree.XML(order.orderPicture(orderid=order_id)).find("Order")

        save_cancel_receipt(
            pos_id,
            order_picture,
            tender_id,
            data
        )

        from posactions import get_printer_receipt
        printer_receipt = get_printer_receipt()
        printer_receipt.print_tef_tender_receipt(
            pos_id=str(pos_id),
            tender_detail=data_cancel,
            fiscalization_type="APOS",
            print_customer_receipt=True,
        )

        set_eft_cache(
            pos_id=pos_id,
            payment_data=data_cancel,
            tender_id=tender_id,
            order_id=order_id,
        )

        logger.info("Success cancel transactions mobile: {0}".format(data))
    except Exception as _:
        logger.info("Error cancel transactions mobile: {0}".format(data))
    finally:
        confirm_finish_eft_transactions(pos_id, "1")
