from xml.etree import cElementTree as eTree
from sysactions import get_user_information

from model.customexception import NotFoundUserError
from thread_local import (
    set_thread_var,
    get_thread_var,
    get_current_model,
)


def get_current_operator_level():
    if get_thread_var("user_level"):
        return get_thread_var("user_level")

    model = get_current_model()
    pos_user_id = int(model.find("Operator").get('id'))
    if not pos_user_id:
        return 0

    user_level = get_user_level(user_id=pos_user_id)
    set_thread_var("user_level", user_level)

    return user_level


def get_user_level(user_id):
    if user_id is None:
        return None

    user_xml_str = get_user_information(user_id)
    if user_xml_str is None:
        raise NotFoundUserError("USER_NOT_FOUND")

    user_xml = eTree.XML(user_xml_str)
    user_element = user_xml.find("user")
    user_level = int(user_element.attrib["Level"])

    return user_level
