from bustoken import TK_SITEF_ADD_PAYMENT
from msgbus import FM_PARAM, TK_SYS_ACK
from mw_helper import show_message_dialog
from sysactions import get_used_service, show_messagebox, close_asynch_dialog
from systools import sys_log_exception


def request_eft(pos_id, mb_context, model, is_credit, amount, _eft_events, is_mercadopago=False):
    order = model.find("CurrentOrder/Order")
    totaled_state = order.findall("StateHistory/State[@state='TOTALED']")[-1]
    last_totaled = totaled_state.get("timestamp").replace("-", "").replace(":", "")

    if is_credit:
        tender_type = 1
    else:
        tender_type = 122 if is_mercadopago else 2

    order_id = order.get("orderId")
    tender_seq_id = len(order.find("TenderHistory").findall("Tender"))
    fiscal_date = last_totaled[:8]
    fiscal_time = last_totaled[9:15]
    operator = model.find("Operator").get("id")
    eft_name = get_used_service(model, "eft")

    dialog_id = show_message_dialog(pos_id, "$INFORMATION", "$WAITING_SITEF_ADD_PAYMENT", "NOCONFIRM", True)
    try:
        component_name = eft_name or "Sitef%02d" % int(pos_id)
        evt_data = [eft_name, None, pos_id, order_id]
        _eft_events.append(evt_data)

        data = "%s;%s;%s;%s;%s;%s;%s;%s;%s" % (str(pos_id), str(order_id), str(operator), str(tender_type), str(amount),
                                               fiscal_date, fiscal_time, tender_seq_id, False)
        ret = mb_context.MB_EasySendMessage(component_name, TK_SITEF_ADD_PAYMENT, FM_PARAM, data)
        if ret.token != TK_SYS_ACK:
            return
        else:
            return ret.data
    except Exception as _: # noqa
        show_messagebox(pos_id, "$ERROR_PROCESSING_TEF", "$EFT", asynch=True, buttons="$OK")
        sys_log_exception("Error processing TEF")
    finally:
        close_asynch_dialog(pos_id, dialog_id)
