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

import json

from bustoken import (
    TK_SLCTRL_PMGR_RUPTURE_UPDATE_DAILY_DISHES,
    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_daily_dishes(
    pos_id,                 # type: str
    removed_dishes_json,    # type: str
    added_dishes_json,      # type: str
):
    # type: (...) -> None

    try:
        removed_dishes = json.loads(removed_dishes_json)
        added_dishes = json.loads(added_dishes_json)

        ruptured = []
        added = []
        for added_dish in added_dishes:
            if added_dish["product_quantity"] == 0:
                ruptured.append(added_dish["product_code"])
            else:
                added.append(added_dish)

        user_id = get_rupture_user_id_with_validation(pos_id=pos_id)

        if len(added) > 0 or len(removed_dishes) > 0:
            dishes_changes_json = json.dumps(
                {
                    'unset': removed_dishes,
                    'set': added
                }
            )

            data = '\0'.join((dishes_changes_json, user_id)).encode("utf-8")
            msg = mb_context.MB_EasySendMessage(
                dest_name="ORDERMGR",
                token=TK_SLCTRL_PMGR_RUPTURE_UPDATE_DAILY_DISHES,
                format=FM_PARAM,
                data=data
            )
            if msg.token == TK_SYS_NAK:
                raise UpdateRuptureException(msg.data)

        if len(ruptured) > 0:
            rupture_status_json = json.dumps(
                {
                    "user_id": user_id,
                    "enabled": [],
                    "disabled": ruptured,
                }
            )
            msg = mb_context.MB_EasySendMessage(
                dest_name="ORDERMGR",
                token=TK_SLCTRL_PMGR_RUPTURE_UPDATE_ITEMS,
                format=FM_PARAM,
                data=rupture_status_json.encode("utf-8"))
            if msg.token == TK_SYS_NAK:
                raise UpdateRuptureException(msg.data)

        show_messagebox(
            posid=pos_id,
            message="$DAILY_DISHES_UPDATE_SUCCESS"
        )
    except StopAction:
        pass
    except Exception as e:
        logger.exception('[save_daily_dishes] Exception {}'.format(e))
        show_messagebox(
            posid=pos_id,
            message="$DAILY_DISHES_UPDATE_ERROR",
            buttons="$EXIT",
        )
