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

import json

from bustoken import TK_SLCTRL_PMGR_RUPTURE_UPDATE_ITEMS
from msgbus import (
    FM_PARAM,
    TK_SYS_NAK,
)
from sysactions import (
    StopAction,
    action,
    show_messagebox,
)

from model.customexception import UpdateRuptureException
from .rupture_common import get_rupture_user_id_with_validation
from .. import (
    logger,
    mb_context,
)


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

    try:
        enabled_codes_json = json.loads(enabled_parts)
        disabled_codes_json = json.loads(disabled_parts)

        user_id = get_rupture_user_id_with_validation(pos_id=pos_id)
        rupture_status_json = json.dumps({
            "user_id": user_id,
            "enabled": list(map(lambda item: item["product_code"], enabled_codes_json)),
            "disabled": list(map(lambda item: item["product_code"], disabled_codes_json)),
        })
        data = rupture_status_json
        msg = mb_context.MB_EasySendMessage("ORDERMGR", TK_SLCTRL_PMGR_RUPTURE_UPDATE_ITEMS, FM_PARAM, data)
        if msg.token == TK_SYS_NAK:
            raise UpdateRuptureException(msg.data)

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