from time import sleep
from typing import Any


import pyscripts
from sysactions import (
    get_model,
    has_current_order,
)


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

    from msgbusboundary import MsgBusTableService as tableService
    selected_table = tableService().get_selected_table(pos_id=pos_id)
    if selected_table is not None:
        tableService().store_service(
            pos_id=pos_id,
            table_id=selected_table.id,
        )
        _send_table_modified_event(
            pos_id=pos_id,
        )


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

    _create_table_modified_event(
        pos_id=pos_id,
        table_picture='0',
    )

    _wait_model_update(
        pos_id=pos_id,
        model_update_validation=has_current_order,
    )


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

    event_xml = """<Event subject="POS{}" type="TABLE_MODIFIED">
                        <TABLE_MODIFIED>
                           {}
                        </TABLE_MODIFIED>
                   </Event>""".format(pos_id, table_picture)
    pyscripts.mbcontext.MB_EasyEvtSend(
        subject="POS{}".format(int(pos_id)),
        type="TableSelected",
        xml=event_xml,
    )


def _wait_model_update(
    pos_id,                     # type: str
    model_update_validation,    # type: Any
):
    # type: (...) -> None

    for _ in range(0, 5):
        model = get_model(posid=pos_id)
        if model_update_validation(model):
            sleep(0.1)
            continue

        break
