package com.lutao.cloud.iot.mqtt.core.server.broker;

import com.lutao.cloud.iot.mqtt.core.server.dispatcher.IMqttMessageDispatcher;
import com.lutao.cloud.iot.mqtt.core.server.event.IMqttMessageListener;
import com.lutao.cloud.iot.mqtt.core.server.model.model.Message;
import lombok.extern.slf4j.Slf4j;
import org.tio.core.ChannelContext;

import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Objects;

/**
 * broker 消息监听转发
 */
@Slf4j
public class MqttBrokerMessageListener implements IMqttMessageListener {
    private final IMqttMessageDispatcher dispatcher;

    public MqttBrokerMessageListener(IMqttMessageDispatcher dispatcher) {
        this.dispatcher = Objects.requireNonNull(dispatcher, "MqttMessageDispatcher is null.");
    }

    @Override
    public void onMessage(ChannelContext context, String clientId, Message message) {
        Charset charset = Charset.forName("utf-8");
        CharBuffer charBuffer = charset.decode(message.getPayload());
        String s = charBuffer.toString();
//        log.info("send clientId:{} message:{}",clientId,s);
        dispatcher.send(message);
    }

}
