package com.imdroid.beidou_fwd.task;


import com.imdroid.beidou_fwd.entity.ZNYMQTTData;
import com.imdroid.beidou_fwd.service.MQTTClient;
import com.imdroid.common.util.Des3Utils;
import com.imdroid.common.util.GsonUtil;
import com.imdroid.common.util.NumberUtils;
import com.imdroid.secapi.dto.GnssCalcData;
import com.imdroid.secapi.dto.GnssStatusMsgMapper;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
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.time.format.DateTimeFormatter;
import java.util.List;

@Component
@Configuration
@EnableScheduling
public class ZNYMQTTForwarder extends Forwarder {
    static final String FORWARDER_NAME = "中南院MQTT";
    final DateTimeFormatter formatterMs = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

    static byte[] key = new byte[] { (byte) 0x8c, (byte) 0xc7, 0x2b, 0x05, 0x70, 0x5d, 0x5c, 0x46, (byte) 0xf4, 0x12, (byte) 0xaf, (byte) 0x8c, (byte) 0xbe,
            (byte) 0xd5, 0x5a, (byte) 0xad, (byte) 0x8c, (byte) 0xc7, 0x2b, 0x05, 0x70, 0x5d, 0x5c, 0x46 };
    static byte[] iv = new byte[] { 0x66, 0x7b, 0x02, (byte) 0xa8, 0x5c, 0x61, (byte) 0xc7, (byte) 0x86 };

    @Value("${zny.mqtt.brokerUrl}")
    private String brokerUrl;
    @Value("${zny.mqtt.username}")
    private String username;
    @Value("${zny.mqtt.password}")
    private String password;
    @Value("${zny.mqtt.clientid}")
    private String clientid;

    @Autowired
    GnssStatusMsgMapper statusMsgMapper;
    MQTTClient mqttClient;

    @PostConstruct
    void registerMe() throws MqttException {
        init(FORWARDER_NAME, "MQTT "+brokerUrl,4,FWD_DEVICE_ALIAS_NAME,30);
        mqttClient = new MQTTClient(brokerUrl, username, password,clientid);
        try{
            mqttClient.connect();
        }
        catch (Exception e){
            logger.error("zny mqtt connect failed: {}",e.toString());
        }
    }

    /**
     * 每半小时转发GNSS解算结果
     */
    //@Scheduled(cron = "0 0 0/1 * * ?") // 每小时执行一次
    @Scheduled(cron = "0 0/30 * * * ?") // 每30分钟执行一次
    private void forwardGnss() {
        logger.debug("zny mqtt forwardGnss");
        if(mqttClient.isConnected()) forwardCurrentGnss();
        else{
            try{
                mqttClient.connect();
            }
            catch (Exception e){
                logger.error("zny mqtt connect failed: {}",e.toString());
            }
        }
    }

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

        for (GnssCalcData locationRecord : records) {
            ZNYMQTTData tranData = new ZNYMQTTData();
            tranData.setTimestamp(locationRecord.getCreatetime().format(formatterMs));
            double n = NumberUtils.scale(locationRecord.getRposn(), 2);
            double e = NumberUtils.scale(locationRecord.getRpose(), 2);
            double d = NumberUtils.scale(locationRecord.getRposd(), 2);
            tranData.setRposn(n);
            tranData.setRpose(e);
            tranData.setRposu(d);
            String json = GsonUtil.toJson(tranData);
            String cryptJson = Des3Utils.encrypt(json,key,iv);
            logger.info("forward to ZNY mqtt: {}, {}",json, cryptJson);
            String topic = "/GnssData/"+locationRecord.getDeviceid()+"/Increment";
            try {
                if(!mqttClient.publish(topic, cryptJson)) break;
                Thread.sleep(20);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            sendNum++;
        }

        return sendNum;
    }


}
