package com.uavps.framework.udp;

import com.uavps.common.utils.StringUtils;
import com.uavps.common.utils.spring.SpringUtils;
import com.uavps.framework.config.UdpConfig;
import com.uavps.framework.udp.utils.UdpDataUtils;
import com.uavps.framework.utils.UdpUtils;
import com.uavps.system.service.IUavpsAircraftService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.time.Instant;


/**
 * @Author MBQ
 * @Date: 2025/1/9
 * @Description:
 * @Version: 1.0
 **/
@Component
public class UdpServerService {

    private static final Logger log = LoggerFactory.getLogger(UdpServerService.class);

    private final UdpConfig udpConfig = SpringUtils.getBean(UdpConfig.class);


    private final IUavpsAircraftService uavpsAircraftService = SpringUtils.getBean(IUavpsAircraftService.class);

    private static final DatagramSocket INSTANCE;

    static {
        try {
            Integer port = SpringUtils.getBean(UdpConfig.class).getPort();
            INSTANCE = new DatagramSocket(port);
            log.info("UDP Server started on port:  {}", port);
        } catch (SocketException e) {
            throw new RuntimeException("Failed to start UDP server", e);
        }
    }

    public void receive(Session session) {
        try {
            //创建一个服务端对象，注册端口
            //创建一个数据包对象，用于接收数据
            byte[] data = new byte[1024];
            DatagramPacket packet = new DatagramPacket(data, data.length);

            String uavData = "";
            long initMilli = Instant.now().toEpochMilli();

            while (true) {

                //使用数据包接收客户端发送的数据
                INSTANCE.receive(packet);
                // 设置初始时间，用于计算每个数据的时间差
                if(TaskInfo.INSTANCE.getInitFlag()){
                    initMilli = Instant.now().toEpochMilli();
                    log.info("任务Id：{}，任务开始，开始时间是：{}", TaskInfo.INSTANCE.getBizId(), initMilli);
                }
                uavData = new String(data, 0, packet.getLength());
                byte[] remoteData = UdpDataUtils.hexStringToBytes(uavData);
                // 将日志条目放入队列
                long lastTime = Instant.now().toEpochMilli() - initMilli;
                String jsonResult = UdpUtils.getJson(remoteData);
                if(StringUtils.isEmpty(jsonResult)){ // 如果解析完数据为null 则跳过
                    continue;
                }
                TaskInfo.INSTANCE.getLogQueue().add(new TaskInfo.LogEntry(jsonResult, lastTime));
                TaskInfo.INSTANCE.setLastTime(lastTime);
                session.getBasicRemote().sendText(jsonResult);
            }
        } catch (IOException e) {
            log.error("UdpServerService.receive error", e);
            throw new RuntimeException(e);
        }
    }
}
