package com.njzscloud.common.localizer.tuqiang.listener;

import com.njzscloud.common.localizer.contant.LocalizerType;
import com.njzscloud.common.localizer.jt808.message.SearchDeviceInfoMessage;
import com.njzscloud.common.localizer.jt808.message.TerminalMessageBody;
import com.njzscloud.common.localizer.jt808.message.TerminalTxtMessage;
import com.njzscloud.common.localizer.jt808.support.JT808MessageListener;
import com.njzscloud.common.mqtt.util.Mqtt;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TuqiangListeners extends JT808MessageListener {

    public TuqiangListeners() {
        super(LocalizerType.Tuqiang);
    }

    /**
     * 终端文本信息汇报消息
     */
    @Override
    public void onTxtReport(TerminalMessageBody message) {
        byte[] body = message.getBody();
        ByteBuf byteBuf = Unpooled.wrappedBuffer(body);
        try {
            TerminalTxtMessage terminalTxtReportMsg = new TerminalTxtMessage(byteBuf);
            String txt = terminalTxtReportMsg.getTxt();
            log.info("终端文本信息汇报消息: {}", txt);
            SearchDeviceInfoMessage deviceInfo = SearchDeviceInfoMessage.parse(txt);
            if (deviceInfo != null) {
                String terminalId = message.getTerminalId();
                deviceInfo.setTerminalId(terminalId);

                Mqtt.publish(terminalId + "/device_info", deviceInfo);
            }
        } catch (Exception e) {
            byteBuf.release();
        }
    }
}
