package com.imdroid.beidou_fwd.task;

import com.imdroid.beidou_fwd.entity.GZYData;
import com.imdroid.beidou_fwd.service.UDPClient;
import com.imdroid.common.util.GsonUtil;
import com.imdroid.common.util.NumberUtils;
import com.imdroid.secapi.dto.GnssCalcData;
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 GZYForwarder extends Forwarder{
    static final String FORWARDER_NAME = "贵州交勘院UDP";
    @Value("${gzy.server.host}")
    private String host;

    @Value("${gzy.server.port}")
    private int port;

    UDPClient udpClient;

    @PostConstruct
    void registerMe(){
        init(FORWARDER_NAME, "UDP "+host+":"+port,2,true,30);
        udpClient = new UDPClient();
        udpClient.init(host, port);
    }
    /**
     * 每半小时转发GNSS解算结果
     */
    @Scheduled(cron = "0 0/30 * * * ?") // 每30分钟执行一次
    private void forwardGnss() {
        logger.info("gzy UDP forwardGnss");
        forwardCurrentGnss();
    }

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

        for(GnssCalcData locationRecord: records) {
            GZYData gzyData = new GZYData();
            gzyData.setIdentityName(locationRecord.getDeviceid());
            GZYData.Data tranData = new GZYData.Data();
            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);
            gzyData.setTranData(tranData);
            String msg = "JGKJ" + GsonUtil.toJson(gzyData) + "#!";
            logger.info("forward to GZY");
            logger.info(msg);
            udpClient.sendMessage(msg);
            sendNum++;
        }
        return sendNum;
    }

}
