import logging
from datetime import datetime

from bustoken import (
    TK_ELECTRONIC_PAYMENT_CONNECTIVITY_TEST,
    TK_ELECTRONIC_PAYMENT_GET_ELECTRONIC_TYPES,
    TK_ELECTRONIC_PAYMENT_GET_NAME,
)
from msgbus import (
    TK_SYS_ACK,
    TK_SYS_NAK
)
from sysactions import (
    action,
    show_messagebox
)
from typing import (
    Any,
    Union
)

from .. import mb_context
from actions.eft import get_electronic_payment_component_name

logger = logging.getLogger("PosActions")


@action
def check_tef_connectivity(pos_id, show_dialog="false"):
    try:
        show_dialog = show_dialog.lower() == "true"

        component_name = get_electronic_payment_component_name(pos_id=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_ELECTRONIC_PAYMENT_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.data).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 get_available_tefs(
    pos_id      # type: Any[Union[str, int]]
):
    # type: (...) -> str

    component_name = get_electronic_payment_component_name(pos_id=pos_id)
    if not component_name:
        return "{}"

    try:
        ret = mb_context.MB_EasySendMessage(
            dest_name=component_name,
            token=TK_ELECTRONIC_PAYMENT_GET_ELECTRONIC_TYPES,
            data=""
        )
        if ret.token == TK_SYS_ACK:
            return ret.data
        return "{}"
    except Exception as _:
        return "{}"


@action
def get_eft_processor_name(
    pos_id,     # type: str
):
    # type: (...) -> str

    try:
        component_name = get_electronic_payment_component_name(pos_id=pos_id)
        response = mb_context.MB_EasySendMessage(
            dest_name=component_name,
            token=TK_ELECTRONIC_PAYMENT_GET_NAME,
            data=pos_id,
        )
        if response.token == TK_SYS_ACK:
            return str(response.data)

    except Exception as ex:
        logger.warning("Error get eft processor name. Exception: {}".format(ex))

    return ""
