# -*- 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_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 = int(get_rupture_user_id_with_validation(pos_id=pos_id))
        product_service = get_product_service()
        product_service.update_items(
            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)),
        )

        show_messagebox(
            posid=pos_id,
            message="$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")
