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

from bustoken import TK_RUPTURA_UPDATE_ITEMS
from msgbus import (
    FM_PARAM,
    TK_SYS_NAK,
)
from sysactions import (
    action,
    get_custom,
    get_model,
    get_operator_session,
    show_messagebox,
)
from typing import Any

from .. import logger
from .. import mb_context
from actions.util.get_menu_user_logged import get_menu_manager_authenticated_user
from model.customexception import UpdateRuptureException


@action
def save_rupture(
    pos_id,                 # type: str
    enabled_ingredients,    # type: str
    disabled_ingredients,   # type: str
):
    # type: (...) -> None

    model = get_model(pos_id)

    try:
        enabled_ingredients_json = json.loads(enabled_ingredients)
        disabled_codes_json = json.loads(disabled_ingredients)
        rupture_status_json = json.dumps({'enabled': enabled_ingredients_json, 'disabled': disabled_codes_json})
        last_manager_auth = get_custom(model, 'Last Manager ID') or get_menu_manager_authenticated_user(int(pos_id))
        operator = get_operator_session(model) or ''
        user_id = '{} / {}'.format(last_manager_auth, operator)
        data = '\0'.join(map(str, [rupture_status_json, user_id, pos_id]))
        msg = mb_context.MB_EasySendMessage("Ruptura", TK_RUPTURA_UPDATE_ITEMS, FM_PARAM, data)
        if msg.token == TK_SYS_NAK:
            raise UpdateRuptureException(msg.data)

        show_messagebox(pos_id, "$RUPTURE_UPDATE_SUCCESS")
    except (Exception, UpdateRuptureException) as e:
        logger.exception('[save_rupture] Exception {}'.format(e))
        show_messagebox(pos_id, "$ERROR_GETTING_DATA", buttons="$EXIT")
