from sysactions import (
    action,
    get_model,
    get_posot,
    check_current_order,
    show_messagebox,
)
from posot import OrderTakerException

from actions.discount.clean_discounts import clean_order_payments
from actions.order.must_sync_ui import must_sync_ui


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

    try:
        must_sync_ui(
            pos_id=pos_id,
            different_than="TOTALED",
        )
        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(
            posid=pos_id,
            message="$ERROR_CODE_INFO|%d|%s" % (ex.getErrorCode(), ex.getErrorDescr()),
        )
