from xml.etree import cElementTree as eTree

from posot import OrderTakerException
from sysactions import (
    action,
    show_messagebox,
)

from actions.discount.clean_discounts import clean_order_payments
from actions.order.must_sync_ui import must_sync_ui
from api.order import get_order_service
from thread_local import get_current_model


@action
def do_back_from_total(pos_id, *args):
    model = get_current_model()
    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
        )

        order_service = get_order_service(pos_id=pos_id)
        xml_order = order_service.reopen_order()

        return eTree.tostring(xml_order).decode("utf-8")

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