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

from sysactions import (
    action,
    get_model,
    get_custom,
    get_operator_session,
    show_messagebox
)
from bustoken import TK_RUPTURA_UPDATE_DAILY_DISHES
from msgbus import (
    TK_SYS_NAK,
    FM_PARAM
)

from .. import logger
from .. import mb_context
from model.customexception import UpdateRuptureException


@action
def save_daily_dishes(
    pos_id,                 # type: str
    removed_dishes_json,    # type: str
    added_dishes_json       # type: str
):
    # type: (...) -> None

    model = get_model(pos_id)

    try:
        removed_dishes = json.loads(removed_dishes_json)
        added_dishes = json.loads(added_dishes_json)
        dishes_changes_json = json.dumps(
            {
                'unset': removed_dishes,
                'set': added_dishes
            }
        )

        last_manager_authorization = get_custom(
            model=model,
            key='Last Manager ID'
        )
        operator = get_operator_session(model) or None
        user_id = last_manager_authorization or operator or ''
        formatted_user_id = '{}'.format(user_id)
        data = '\0'.join(map(str, [dishes_changes_json, formatted_user_id]))
        msg = mb_context.MB_EasySendMessage(
            dest_name="Ruptura",
            token=TK_RUPTURA_UPDATE_DAILY_DISHES,
            format=FM_PARAM,
            data=data
        )
        if msg.token == TK_SYS_NAK:
            raise UpdateRuptureException(msg.data)

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