package com.huashe.park.application.mqtt;

import java.nio.charset.StandardCharsets;

import javax.annotation.PostConstruct;

import net.dreamlu.iot.mqtt.spring.client.MqttClientTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;
import com.huashe.park.application.engine.impl.VideoTrailEngine;
import com.huashe.park.common.consts.BDConst;
import com.huashe.park.infrastructure.cfg.mqtt.MqttCfg;

import net.dreamlu.iot.mqtt.codec.MqttQoS;
import net.dreamlu.iot.mqtt.core.client.MqttClientCreator;
import net.dreamlu.iot.mqtt.spring.client.MqttClientSubscribe;
import net.dreamlu.iot.mqtt.spring.client.event.MqttConnectedEvent;
import net.dreamlu.iot.mqtt.spring.client.event.MqttDisconnectEvent;

@Service
@ConditionalOnBean(MqttClientTemplate.class)
@ConditionalOnProperty(name = "evt-fusion.video-trail-engine.enable", havingValue = "true")
public class UWBLocationListener {
    private static final Logger logger = LoggerFactory.getLogger(UWBLocationListener.class);

    @Autowired
    private MqttClientCreator mqttClientCreator;

    @Autowired
    private VideoTrailEngine videoTrailEngine;

    @PostConstruct
    public void init() {
        videoTrailEngine.start();
    }

    @EventListener
    public void onConnected(MqttConnectedEvent event) {
        logger.info("MqttConnectedEvent:{}", event);
    }

    @EventListener
    public void onDisconnect(MqttDisconnectEvent event) {
        // 离线时更新重连时的密码，适用于类似阿里云 mqtt clientId 连接带时间戳的方式
        logger.info("MqttDisconnectEvent:{}", event);
        // 在断线时更新 clientId、username、password
        mqttClientCreator.clientId("newClient" + System.currentTimeMillis()).username("newUserName")
            .password("newPassword");
    }

    @MqttClientSubscribe(value = BDConst.MQTT_TOPIC.UWB_VIDEO_TRACE_POINT_TOPIC, qos = MqttQoS.QOS0)
    public void subQos1(String topic, byte[] payload) {
        videoTrailEngine.trailTag(JSON.parseObject(payload));
    }
}
