from typing import Optional

from sysactions import send_message, check_operator_logged, get_model, action
from msgbus import MBException, TK_CDRAWER_OPEN

from thread_local import get_current_model

@action
def doOpenDrawer(
    pos_id,               # type: str
    check_oper="true",    # type: Optional[str]
    **kwargs
):
    # type: (...) -> None

    model = get_current_model()
    if check_oper == "true":
        check_operator_logged(
            posid=pos_id,
            model=model,
            can_be_blocked=False,
            need_logged=kwargs.get("need_logged", True),
        )

    drawers = model.findall("CashDrawer")
    for drawer in drawers:
        from threading import Thread
        open_drawer_thread = Thread(target=thread_open_drawer, args=(drawer,))
        open_drawer_thread.daemon = True
        open_drawer_thread.start()


def thread_open_drawer(drawer):
    try:
        send_message(drawer.get("name"), TK_CDRAWER_OPEN)
    except MBException:
        pass
