from xml.etree import cElementTree as eTree

from messagebus import MessageBus, Message, DataType, DefaultToken, TokenCreator, TokenPriority

TK_POS_GETMODEL = TokenCreator.create_token(
    priority=TokenPriority.high,
    message_group="5",
    number="1",
)


class PosModelRetriever(object):
    def __init__(
        self,
        message_bus,  # type: MessageBus
    ):
        self.message_bus = message_bus

    def get_model(
        self,
        pos_id,  # type: int
    ):
        reply = self.message_bus.send_message(
            component="POS{}".format(pos_id),
            message=Message(
                token=TK_POS_GETMODEL,
                data_type=DataType.param,
                data=f"{pos_id}".encode("utf-8"),
            ),
        )
        if reply.token != DefaultToken.TK_SYS_ACK:
            raise Exception("Could not retrieve state of pos '{}'".format(pos_id))
        return eTree.XML(reply.data)
