from sysactions import (
    action,
    get_model,
    get_posot,
    check_current_order,
    show_messagebox,
    show_confirmation,
    StopAction
)
from posot import OrderTakerException
from custom_sysactions import user_authorized_to_execute_action

from actions.discount.clean_discounts import clean_order_payments
from actions.void.utils import get_void_reason_id, void_order


@action
def do_back_from_total(pos_id, void_reason=5, *args):
    model = get_model(pos_id)
    order = model.find("CurrentOrder/Order")

    try:
        clean_order_payments(
            pos_id=pos_id,
            order=order,
            check_manual_discounts=True
        )
        check_current_order(pos_id, model=model)
        get_posot(model).reopenOrder(int(pos_id))

    except OrderTakerException as ex:
        show_messagebox(pos_id, message="$ERROR_CODE_INFO|%d|%s" % (ex.getErrorCode(), ex.getErrorDescr()))


@user_authorized_to_execute_action
def void_order_with_payments(pos_id, void_reason):
    confirm = show_confirmation(pos_id, "$CANNOT_CHANGE_ORDER_WITH_PAYMENTS", timeout=180000)
    if confirm:
        void_reason = get_void_reason_id(pos_id, void_reason)
        if not void_reason:
            raise StopAction()

        void_order(pos_id, void_reason=void_reason)
