# -*- coding: utf-8 -*-

from sysactions import action, show_messagebox  # noqa
from bustoken import TK_POS_UPDATER_PERFORM_LOADER_UPDATE
from msgbus import (
    MBMessage,
    TK_SYS_NAK,
)  # noqa

from .update_util import show_nak_message
from .. import mb_context


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

    resp = show_messagebox(
        posid=pos_id,
        message="$UPDATE_LOADERS_MESSAGE_QUESTION",
        buttons="$OK|$CANCEL",
    )
    if resp == 1:
        return

    msg = _send_update_message()
    if msg.token == TK_SYS_NAK:
        response_message = msg.data
        show_nak_message(
            pos_id=pos_id,
            update_key="$UPDATE_LOADERS_",
            message=response_message,
        )


def send_update_loaders_with_retry(
    pos_id,    # type: str
):
    # type: (...) -> None

    while True:
        msg = _send_update_message()
        if msg.token == TK_SYS_NAK:
            resp = show_messagebox(
                posid=pos_id,
                message="$UPDATE_LOADERS_ERROR_TRY_AGAIN",
                buttons="$YES|$NO",
            )
            if resp == 1:
                return


def _send_update_message():
    # type: (...) -> MBMessage

    timeout = 60000000 * 5
    msg = mb_context.MB_EasySendMessage(
        dest_name="PosUpdater",
        token=TK_POS_UPDATER_PERFORM_LOADER_UPDATE,
        timeout=timeout,
    )
    return msg
