from xml.etree import cElementTree as eTree

from bustoken import TK_SITEF_ADD_PAYMENT
from msgbus import (
    FM_PARAM,
    TK_SYS_ACK,
    MBEasyContext,
)
from mw_helper import show_message_dialog
from sysactions import (
    get_used_service,
    show_messagebox,
    close_asynch_dialog,
)
from systools import sys_log_exception
from typing import (
    Optional,
    List,
)

from actions.eft import get_tender_id


def request_eft(
    pos_id,                     # type: str
    mb_context,                 # type: MBEasyContext
    model,                      # type: eTree.XML
    is_credit,                  # type: bool
    amount,                     # type: float
    _eft_events,                # type: List
    is_mercadopago=False,       # type: bool
    is_table_service=False,     # type: bool
):
    # type: (...) -> Optional[str]

    from poslistener import eft_status_finish

    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")
    all_tenders = order.find("TenderHistory").findall("Tender")
    tender_id = get_tender_id(all_tenders, is_table_service)

    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_id,
            False
        )

        response = mb_context.MB_EasySendMessage(component_name, TK_SITEF_ADD_PAYMENT, FM_PARAM, data)
        if response.token != TK_SYS_ACK:
            return

        return response.data
    except Exception as _: # noqa
        show_messagebox(pos_id, "$ERROR_PROCESSING_TEF", "$EFT", asynch=True, buttons="$OK")
        sys_log_exception("Error processing TEF")
    finally:
        eft_status_finish([pos_id])
        close_asynch_dialog(pos_id, dialog_id)



