from sysactions import (
    action,
    get_model,
    get_podtype,
    get_posot,
)

from actions.kiosk import do_void_kiosk_order
from actions.void.do_void_order import do_void_order


@action
def handle_abandon_order(pos_id):
    try:
        model = get_model(pos_id)
        pod_type = get_podtype(model)
        is_totem_order = pod_type == "TT"
        if is_totem_order:
            return do_void_kiosk_order(pos_id)

        order_state_history = model.find("CurrentOrder/Order/StateHistory")
        order_states = order_state_history.findall(".//State")
        order_was_saved = any([True for state in order_states if state.get("state") == "STORED"])
        if order_was_saved:
            pos_ot = get_posot(model)
            pos_ot.storeOrder(pos_id)
            return True

        void_reason = 9
        return do_void_order(
            pos_id,
            void_reason,
            show_cancel_message=False
        )
    except BaseException as _:
        return False
