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

import json

from api.product import get_product_service
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


@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 = int(get_rupture_user_id_with_validation(pos_id=pos_id))

        product_service = get_product_service()
        if added or removed_dishes:
            product_service.update_daily_dishes(
                user_id=user_id,
                to_add=added,
                to_remove=removed_dishes,
            )

        if ruptured:
            try:
                product_service.update_items(
                    user_id=user_id,
                    enabled=[],
                    disabled=ruptured,
                )
            except (Exception,) as ex:
                raise UpdateRuptureException(ex)

        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",
        )
