from xml.etree import cElementTree as eTree

import pyscripts
from mbcontextmessagehandler import MbContextMessageBus
from pos_api import PosService
from typing import Optional

from thread_local import (
    get_thread_var,
    set_thread_var,
    get_current_model,
)


def get_pos_service(
    pos_id,     # type: int
    model=None  # type: Optional[eTree.Element]
):
    # type: (...) -> PosService

    if get_thread_var("pos_service"):
        return get_thread_var("pos_service")

    if model is None:
        model = get_current_model()

    pos_service = PosService(
        message_bus=MbContextMessageBus(mbcontext=pyscripts.mbcontext),
        pos_id=pos_id,
        model=model,
    )

    set_thread_var("pos_service", pos_service)
    return pos_service
