from bustoken import TK_REMOTE_ORDER_GET_POS_ID
from msgbus import (
    FM_PARAM,
    TK_SYS_NAK,
)
from sysactions import send_message
from typing import Optional
from xml.etree import cElementTree as eTree

from api.order import get_order_service

pos_id_remote_order = None


def is_delivery_order(
    pos_id,         # type: str
    order=None,     # type: eTree.Element
):
    # type: (...) -> bool

    order = order or get_order_service(pos_id=pos_id).get_order_picture()
    if order is None:
        return False

    has_remote_order_id = get_remote_id(order=order) is not None
    return has_remote_order_id


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

    remote_order_id = order.find("CustomOrderProperties/OrderProperty[@key='REMOTE_ORDER_ID']")
    if remote_order_id is not None:
        return remote_order_id.get("value")

    manual_order_id = order.find("CustomOrderProperties/OrderProperty[@key='MANUAL_ORDER_ID']")
    if manual_order_id is not None:
        return manual_order_id.get("value")

    return None


def get_pos_id_of_remote_order():
    # type: (...) -> int

    global pos_id_remote_order

    if pos_id_remote_order is not None:
        return pos_id_remote_order

    msg = send_message(
        dest_name="RemoteOrder",
        token=TK_REMOTE_ORDER_GET_POS_ID,
        format=FM_PARAM,
        timeout=100000,
    )
    if msg.token == TK_SYS_NAK:
        return 0

    pos_id_remote_order = int(msg.data)
    return pos_id_remote_order
