package com.imdroid.beidou_fwd.task;


import com.imdroid.beidou_fwd.entity.GZYMQTTData;
import com.imdroid.beidou_fwd.service.MQTTClient;
import com.imdroid.common.util.GsonUtil;
import com.imdroid.common.util.NumberUtils;
import com.imdroid.secapi.dto.GnssCalcData;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Configuration
@EnableScheduling
public class GZYMQTTForwarder extends Forwarder {
    static final String FORWARDER_NAME = "贵州交勘院MQTT";
    @Value("${mqtt.server.brokerUrl}")
    private String brokerUrl;
    @Value("${mqtt.server.username}")
    private String username;
    @Value("${mqtt.server.password}")
    private String password;
    @Value("${mqtt.server.clientid}")
    private String clientid;
    @Value("${mqtt.server.topic}")
    private String topic;


    MQTTClient mqttClient;

    @PostConstruct
    void registerMe() throws MqttException {
        init(FORWARDER_NAME, "MQTT "+brokerUrl,2,true,30);
        mqttClient = new MQTTClient(brokerUrl, username, password,clientid,topic);
        mqttClient.connect();
    }

    /**
     * 每半小时转发GNSS解算结果
     */
    @Scheduled(cron = "0 0/30 * * * ?") // 每30分钟执行一次
    private void forwardGnss() {
        logger.info("gzy mqtt forwardGnss");
        forwardCurrentGnss();
    }

    @Override
    int send(String projectId, List<GnssCalcData> records, LocalDateTime sentTime) {
        int sendNum = 0;

        for (GnssCalcData locationRecord : records) {
            GZYMQTTData tranData = new GZYMQTTData();
            tranData.setCollectTime(locationRecord.getCreatetime().format(formatter));
            double n = NumberUtils.scale(locationRecord.getRposn(), 2);
            double e = NumberUtils.scale(locationRecord.getRpose(), 2);
            double d = NumberUtils.scale(locationRecord.getRposd(), 2);
            tranData.setX(n);
            tranData.setY(e);
            tranData.setZ(d);
            tranData.setDeviceType(2);
            tranData.setDeviceSn(locationRecord.getDeviceid());
            String json = GsonUtil.toJson(tranData);
            logger.info("forward to GZY mqtt");
            logger.info(json);
            try {
                if(!mqttClient.publish(json)) break;
                Thread.sleep(200);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            sendNum++;
        }

        return sendNum;
    }

}
