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

from sysactions import action, show_messagebox  # noqa

from msgbus import TK_SYS_NAK
from api.pos_updater import get_pos_updater_service
from messagebus import Message
from .update_util import show_nak_message
from ..util.get_menu_user_logged import get_menu_manager_authenticated_user


@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(pos_id=pos_id)
    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(pos_id=pos_id)
        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(
    pos_id,     # type: str
):
    # type: (...) -> Message

    user_id = get_menu_manager_authenticated_user(pos_id=int(pos_id))
    updater_service = get_pos_updater_service(pos_id=pos_id)
    return updater_service.loader_update(user_id=user_id)
