import logging

from gateway_integration_deltagrid.inbound.RpcRouter import RpcRouter
from gateway_transport.mqtt.MqttClientProtocol import MqttClientProtocol

logger = logging.getLogger(__name__)


class DeltaGridMqttCommandListener:
    def __init__(
        self,
        mqttClient:MqttClientProtocol,
        router: RpcRouter,
        commandTopic: str,
    ) -> None:
        self._mqtt = mqttClient
        self._router = router
        self._topic = commandTopic

    async def registerCallbacks(self) -> None:
        logger.info("Starting RPC listener on topic '%s'", self._topic)
        await self._mqtt.subscribe(self._topic, self._onMessage)

    async def _onMessage(self, topic: str, payload: bytes) -> None:
        logger.debug("Received RPC message on %s: %s", topic, payload)
        await self._router.dispatch(payload)
