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

import sysactions
from actions.rupture.get_ruptured_products import has_rupture_items

from bustoken import TK_POS_UPDATER_PERFORM_CATALOG_UPDATE, TK_POS_GET_CATALOG_VERSION_TO_APPLY
from msgbus import TK_SYS_NAK, FM_PARAM


@sysactions.action
def update_menu(pos_id):
    try:
        msg = get_catalog_version_to_apply(True)
        if msg.token == TK_SYS_NAK:
            get_message_update(pos_id, "$UPDATE_MENU_" + msg.data.upper(), buttons="OK")
            raise sysactions.StopAction()

        get_message_update(pos_id, "$UPDATE_MENU_VERSION_AVAILABLE|" + msg.data, buttons="$OK|$CANCEL")
        get_message_update(pos_id, "$UPDATE_MENU_MESSAGE", buttons="$OK|$CANCEL")
        has_rupture_items(pos_id)
        apply_update(pos_id)
    except Exception as _:
        sysactions.sys_log_exception("Error updating menu")
        get_message_update(pos_id, "$UPDATE_MENU_EXCEPTION", buttons="OK")


def get_catalog_version_to_apply(need_backoffice_json=False):
    timeout = 60000000 * 5
    data = str(need_backoffice_json)
    return sysactions.send_message("PosUpdater", TK_POS_GET_CATALOG_VERSION_TO_APPLY, FM_PARAM, data, timeout)


def apply_update(pos_id):
    timeout = 60000000 * 5
    msg = sysactions.send_message("PosUpdater", TK_POS_UPDATER_PERFORM_CATALOG_UPDATE, FM_PARAM, timeout=timeout)
    if msg.token == TK_SYS_NAK:
        get_message_update(pos_id, "$UPDATE_MENU_" + msg.data.upper(), buttons="OK")
        return False

    return True


def get_message_update(pos_id, message, buttons="OK", timeout=60000):
    resp = sysactions.show_messagebox(pos_id, message, buttons=buttons, timeout=timeout)
    if resp is None or resp == 1:
        raise sysactions.StopAction()
