from typing import Optional
from xml.etree import cElementTree as eTree

from sysactions import (
    StopAction,
    show_messagebox,
    get_model,
    get_posot,
    get_current_order,
)

from actions.order import synchronize_ui


def must_sync_ui(
    pos_id,             # type: str
    different_than,     # type: str
):
    # type: (...) -> None

    order = _get_order_picture(pos_id=pos_id)

    different_than = different_than.upper()
    if order.get("state") != different_than:
        show_messagebox(
            posid=pos_id,
            message="$ERROR_ORDER_{}_NOT_SYNCHRONIZED".format(different_than),
            buttons="$OK",
        )

        synchronize_ui(
            pos_id=pos_id,
        )

        raise StopAction()


def _get_order_picture(
    pos_id,     # type: Optional[str]
):
    # type: (...) -> Optional[eTree.Element]

    model = get_model(posid=pos_id)
    pos_ot = get_posot(model=model)

    current_order = get_current_order(model=model)
    order_id = current_order.get("orderId")
    order_xml = eTree.XML(
        pos_ot.orderPicture(
            posid=pos_id,
            orderid=order_id,
        )
    )
    return order_xml.find("Order") if order_xml.find("Order") else order_xml
