import logging
import time

from bustoken import TK_ELECTRONIC_PAYMENT_RELEASE_WAIT_CONFIRMATION
from msgbus import FM_PARAM, TK_SYS_ACK
from sysactions import mbcontext

from actions.eft import get_electronic_payment_component_name

logger = logging.getLogger("EftActions")


def release_wait_confirmation(
    pos_id,     # type: str
    status,     # type: str
    data="",    # type: str
):
    # type: (...) -> None

    sitef_comp_name = get_electronic_payment_component_name(pos_id=pos_id)
    data = "{};{};{}".format(str(pos_id), status, data)
    for _ in range(1, 4):
        try:
            ret = mbcontext.MB_EasySendMessage(
                dest_name=sitef_comp_name,
                token=TK_ELECTRONIC_PAYMENT_RELEASE_WAIT_CONFIRMATION,
                format=FM_PARAM,
                data=data,
                timeout=600000000,
            )
            if ret.token == TK_SYS_ACK:
                logger.info("Success confirming finished eft transaction. {}".format(pos_id))
                return

            message = "ACK not received when confirming finish. {} - {} - {}"
            logger.info(message.format(pos_id, ret.token, ret.data))
            time.sleep(1)

        except (Exception,):
            logger.info("Error confirming finish")
