package com.uavps.framework.udp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

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

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final int BUFF_SIZE = 1000; // 总缓冲区大小 接收方设置的是1024，但是按1024发送回报错。。。
    private static final int HEADER_SIZE = 4;   // 序号占4字节
    private static final int DATA_SIZE = BUFF_SIZE - HEADER_SIZE; // 有效数据大小（1020字节）
    private static final int PORT = 9010; // 有效数据大小（1020字节）

    public void send(String message) {
        try {
            DatagramSocket socket = new DatagramSocket();
            InetAddress address = InetAddress.getByName("localhost");

            byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8);
            int totalBytes = messageBytes.length;
            int totalChunks = (int) Math.ceil((double) totalBytes / DATA_SIZE);

            for (int index = 0; index < totalChunks; index++) {
                // 生成4字节ASCII序号（如 "0001"）
                String indexStr = String.format("%04d", index); // 固定4位，前面补0
                byte[] indexBytes = indexStr.getBytes(StandardCharsets.UTF_8);

                // 计算当前分片的数据范围
                int start = index * DATA_SIZE;
                int end = Math.min(start + DATA_SIZE, totalBytes);
                byte[] chunkData = new byte[end - start];
                System.arraycopy(messageBytes, start, chunkData, 0, chunkData.length);

                // 合并序号和数据
                ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFF_SIZE);
                baos.write(indexBytes); // 写入4字节ASCII序号
                baos.write(chunkData);  // 写入数据

                // 发送分片
                byte[] sendData = baos.toByteArray();
                DatagramPacket packet = new DatagramPacket(sendData, sendData.length, address, PORT);
                socket.send(packet);
                logger.info("Sent chunk: {}, size: {}", indexStr, sendData.length);
            }

            // 发送结束包（序号为总块数，内容为 "END"）
//            String endIndexStr = String.format("%04d", totalChunks);
            byte[] endDataBytes = "END".getBytes(StandardCharsets.UTF_8);

            DatagramPacket endPacket = new DatagramPacket(endDataBytes, endDataBytes.length, address, PORT);
            socket.send(endPacket);
            logger.info("Sent END chunk: {}", endDataBytes);

        } catch (IOException e) {
            logger.error("UdpClientService send error", e);
            throw new RuntimeException(e);
        }
    }
}
