package com.ningdatech.carapi.radar.manage;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

import org.apache.log4j.net.SocketServer;
import org.springframework.stereotype.Component;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 车辆位置信息
 *
 * @author CMM
 * @since 2023/11/17 09:35
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RadarManage {

    public String getRadarData() {
        try {
            ServerSocket serverSocket = new ServerSocket(13000, 600, InetAddress.getByName("192.168.6.42"));
            // 设置为0表示无限等待，可以根据需要设置超时时间
            serverSocket.setSoTimeout(6000);
            System.out.println("ServerSocket started on port: " +  13000);
            log.info("ServerSocket started on port: {}", 13000);
            Socket clientSocket = serverSocket.accept();
            System.out.println("Connect Successfully!");
            log.info("Connect Successfully!");

            DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream());
            // 开启保活选项
            clientSocket.setKeepAlive(true);
            byte[] allData;
            while (!clientSocket.isClosed()) {
                // 使用 ByteArrayOutputStream 来收集所有读取的字节
                try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
                    // 使用一个合适的缓冲区大小
                    byte[] data = new byte[4096];
                    int nRead;
                    while ((nRead = dataInputStream.read(data, 0, data.length)) != -1 && buffer.size() < 4096) {
                        buffer.write(data, 0, nRead);
                    }
                    buffer.flush();
                    allData = buffer.toByteArray();
                }
                // 处理从雷达接收到的数据
                if (allData.length > 0) {
                    String dataString = new String(allData, StandardCharsets.UTF_8);
                    System.out.println("Received: " + dataString);
                    log.info("Received: {}", dataString);
                    break;
                }
            }
            // 关闭当前周期的连接
            clientSocket.close();
        } catch (IOException e) {
            return e.getMessage();
        }
        return null;
    }
}
