package com.huashe.park.application.mqtt;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.huashe.park.application.engine.impl.FenceBreakInEngine;
import com.huashe.park.application.engine.impl.PointFusionEngine;
import com.huashe.park.application.engine.impl.RoomBreakInEngine;
import com.huashe.park.infrastructure.cfg.mqtt.MqttCfg;
import com.huashe.park.common.consts.BDConst;
import net.dreamlu.iot.mqtt.codec.MqttQoS;
import net.dreamlu.iot.mqtt.spring.client.MqttClientSubscribe;
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.stereotype.Service;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;

@Service
@ConditionalOnBean(MqttClientTemplate.class)
public class UWBLocationSubscribeListener {
    private static final Logger logger = LoggerFactory.getLogger(UWBLocationSubscribeListener.class);

    @Autowired
    private PointFusionEngine pointFusionEngine;

    @Autowired
    private FenceBreakInEngine fenceBreakInEngine;

    @Autowired
    private RoomBreakInEngine roomBreakInEngine;

    @PostConstruct
    public void init() {
        pointFusionEngine.start();
        fenceBreakInEngine.start();
        roomBreakInEngine.start();
    }

    @MqttClientSubscribe(value = BDConst.MQTT_TOPIC.POINT_LOCATION_TOPIC)
    public void subQos0(String topic, byte[] payload) {
        logger.debug("topic:{} payload:{}", topic, new String(payload, StandardCharsets.UTF_8));
        JSONObject jsonObject = JSON.parseObject(payload);
        pointFusionEngine.push(jsonObject);
        fenceBreakInEngine.generateEvt(JSON.parseObject(payload), payload);
        roomBreakInEngine.generateEvt(JSON.parseObject(payload), payload);
    }

    @MqttClientSubscribe(value = BDConst.MQTT_TOPIC.EVT_LOCATION_TOPIC, qos = MqttQoS.QOS0)
    public void subQos1(String topic, byte[] payload) {
        logger.debug("topic:{} payload:{}", topic, new String(payload, StandardCharsets.UTF_8));
        fenceBreakInEngine.push(JSON.parseObject(payload));
    }

    @MqttClientSubscribe(value = BDConst.MQTT_TOPIC.EVT_ROOM_LOCATION_TOPIC, qos = MqttQoS.QOS0)
    public void subQos2(String topic, byte[] payload) {
        logger.debug("topic:{} payload:{}", topic, new String(payload, StandardCharsets.UTF_8));
        roomBreakInEngine.push(JSON.parseObject(payload));
    }


}
