# -*- coding: utf-8 -*-
import json

import sysactions
from actions.util import get_ruptured_products_from_remote_order
from bustoken import TK_REMOTE_ORDER_GET_RUPTURED_ITEMS
from msgbus import TK_SYS_NAK, FM_PARAM
from typing import List

from .. import logger
from .. import mb_context


@sysactions.action
def get_ruptured_products(pos_id):
    # type: (str) -> str

    try:
        products = {
                "enabledProducts": [],
                "disabledProducts": get_ruptured_products_from_remote_order()
        }

        return json.dumps(products)

    except Exception as e:
        logger.exception('[get_ruptured_products] Exception {}'.format(e))
        sysactions.show_messagebox(pos_id, "$RUPTURE_ERROR", "$INFORMATION")


def _get_ruptured_products_from_json():
    # type: () -> List

    products_list = []
    ruptured_products = _get_ruptured_products(products_list)
    return ruptured_products


def _get_ruptured_products(products):
    # type: (List) -> List

    token = TK_REMOTE_ORDER_GET_RUPTURED_ITEMS
    msg = mb_context.MB_EasySendMessage("RemoteOrder", token, FM_PARAM, json.dumps(products))
    if msg.token == TK_SYS_NAK:
        raise Exception(msg.data)

    return json.loads(msg.data)


def has_rupture_items(pos_id):
    # type: (int) -> None

    rupture_items = get_ruptured_products_from_remote_order()
    if not rupture_items:
        return

    rupture_reset_alert = '$RUPTURE_RESET_UPDATE'
    sysactions.show_messagebox(pos_id, message=rupture_reset_alert, buttons="$OK")
