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

from sysactions import (
    UiOutOfSync,
    get_model,
    get_posot,
    get_current_order,
)

from actions import logger


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()
    state = order.get("state")
    if state != different_than:
        logger.info("Required Order Status: {}. Model Order Status: {}".format(
            different_than,
            state,
        ))

        raise UiOutOfSync(
            pos_id=pos_id,
            custom_message="$ERROR_ORDER_NOT_SYNCHRONIZED",
        )


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

    raise UiOutOfSync(
        pos_id=pos_id,
        reset_model=True,
        custom_message="$ERROR_ORDER_NOT_SYNCHRONIZED",
    )


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
