from xml.etree import cElementTree as eTree

from messagebus import (
    DefaultToken,
    Message,
    MessageBus,
    TokenCreator,
    TokenPriority,
)
from nreports.model.exceptions import UserDataNotFound

TK_USERCTRL_GETINFO = TokenCreator.create_token(
    priority=TokenPriority.low,
    message_group="12",
    number="2",
)  # 18874370


class UserRepository(object):

    def __init__(
        self,
        message_bus: MessageBus,
    ) -> None:

        self._message_bus = message_bus

    def get_user_information(
        self,
        user_id: str,
    ) -> eTree.Element:

        msg = self._message_bus.send_message(
            component="UserControl",
            message=Message(
                token=TK_USERCTRL_GETINFO,
                data=user_id.encode("utf-8"),
            ),
        )
        if msg.token == DefaultToken.TK_SYS_ACK:
            xml_response = eTree.XML(msg.data)
            return xml_response.find("user")

        raise RuntimeError("Could not retrieve info from the UserControl service")

    def get_user_name(
        self,
        user_id: str,
    ) -> str:

        user_data = self.get_user_information(user_id=user_id)
        if user_data is not None:
            return user_data.get("LongName")

        raise UserDataNotFound(user_id=user_id)
