from xml.etree import cElementTree as eTree
from typing import (
    Optional,
)

from messagebus import (
    DefaultToken,
    Message,
    MessageBus,
    TokenCreator,
    TokenPriority,
)

TK_STORECFG_GETFULL = TokenCreator.create_token(
    priority=TokenPriority.low,
    message_group="13",
    number="2",
)  # 19922946


class StoreConfigRepository(object):

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

        self._message_bus = message_bus
        self._store_wide_config: Optional[eTree.Element] = None

    def get_store_wide_config(
        self,
    ) -> eTree.Element:

        if self._store_wide_config:
            return self._store_wide_config

        msg = self._message_bus.send_message(
            component="StoreWideConfig",
            message=Message(token=TK_STORECFG_GETFULL),
        )
        if msg.token == DefaultToken.TK_SYS_ACK:
            self._store_wide_config = eTree.XML(msg.data.decode())
            return self._store_wide_config

        raise RuntimeError("StoreWideConfig not found")
