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.util.List;

@Component
@Configuration
@EnableScheduling
public class GZYForwarder extends Forwarder{
    private final Logger logger = LoggerFactory.getLogger(GZYForwarder.class);

    static final String FORWARDER_NAME = "贵州交勘院";
    @Value("${gzy.server.host}")
    private String host;

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

    UDPClient udpClient;

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

    @Scheduled(cron = "0 40 * * * ?") // 每小时的40分钟执行一次
    //@Scheduled(cron = "0 0/20 * * * ?") // 每20分钟执行一次
    private void forwardHistoryGnss() {
        forwardHistoryGnss(FORWARDER_NAME);
    }

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

        GZYData gzyData = new GZYData();
        gzyData.setIdentityName(projectId);


        for(GnssCalcData locationRecord: records) {
            GZYData.Data tranData = new GZYData.Data();
            tranData.setCollectTime(locationRecord.getCreatetime().format(formatter));
            double n = NumberUtils.scale(locationRecord.getRb562n(), 2);
            double e = NumberUtils.scale(locationRecord.getRb562e(), 2);
            double d = NumberUtils.scale(locationRecord.getRb562d(), 2);
            tranData.setX(n);
            tranData.setY(e);
            tranData.setZ(d);
            gzyData.addData(tranData);
            sendNum++;
        }
        String json = GsonUtil.toJson(gzyData);
        String msg = "JGKJ" + json + "#!";
        logger.info("forward to GZY");
        logger.info(msg);
        udpClient.sendMessage(msg);
        return sendNum;
    }

}
