import logging
from datetime import datetime

from bustoken import TK_SITEF_CONNECTIVITY_TEST, TK_SITEF_AVAILABLE
from msgbus import TK_SYS_ACK, TK_SYS_NAK
from sysactions import action, show_messagebox, get_used_service, get_model

from .. import mb_context

logger = logging.getLogger("PosActions")


@action
def check_tef_connectivity(pos_id, show_dialog="false"):
    try:
        show_dialog = show_dialog.lower() == "true"
        component_name = "Sitef%02d" % int(pos_id)
        data = "{};{};{}".format(pos_id, datetime.now().strftime("%Y%m%d"), datetime.now().strftime('%H:%M:%S'))
        ret = mb_context.MB_EasySendMessage(component_name, TK_SITEF_CONNECTIVITY_TEST, data=data)

        if show_dialog:
            if ret.token == TK_SYS_NAK:
                show_messagebox(pos_id, "$SITEF_IS_NOT_AVAILABLE", "$ERROR")
            else:
                show_messagebox(pos_id, "$SITEF_OK")

        return str(ret.token == TK_SYS_ACK).lower()
    except Exception as ex:
        logger.warning("Error verifying if Electronic Payments is available. Exception: {}".format(ex.message))

        if show_dialog:
            show_messagebox(pos_id, "$SITEF_SERVER_ERROR|{}".format(str(pos_id)), "$ERROR")

        return "false"


@action
def is_tef_available(pos_id):
    model = get_model(pos_id)
    eft_name = get_used_service(model, "eft")

    if eft_name is not None:
        try:
            ret = mb_context.MB_EasySendMessage(eft_name, token=TK_SITEF_AVAILABLE)
            if ret.token == TK_SYS_ACK:
                return ret.data
            return "{}"
        except Exception as _: # noqa
            return "{}"

    return "{}"
