package com.ningdatech.carapi.radar.client;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

import com.ningdatech.carapi.radar.model.entity.RadarData;
import com.ningdatech.carapi.radar.service.IRadarDataService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author CMM
 * 雷达客户端数据处理器
 * @since 2024/09/28 10:32
 */
@Slf4j
public class RadarHandler implements Runnable{
    private final Socket clientSocket;
    private final IRadarDataService radarDataService;
    private final String radarIp;

    public RadarHandler(Socket socket, IRadarDataService radarDataService, String radarIp) {
        this.clientSocket = socket;
        this.radarDataService = radarDataService;
        this.radarIp = radarIp;
    }

    @Override
    public void run() {
        // 获取输入流以读取雷达发送的数据
        try {
            DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream());
            // 开启保活选项
            clientSocket.setKeepAlive(true);
            byte[] allData = readAllBytesFromDataInputStream(dataInputStream);
            // 处理从雷达接收到的数据
            if (allData.length > 0) {
                String dataString = new String(allData, StandardCharsets.UTF_8);
                log.info("Received: {}", dataString);
                RadarData radarData = new RadarData();
                radarData.setRadarIp(radarIp);
                radarData.setData(dataString);
                radarData.setCreateOn(LocalDateTime.now());
                radarData.setUpdateOn(LocalDateTime.now());
                radarDataService.save(radarData);
            }
            // 关闭当前周期的连接
            clientSocket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private byte[] readAllBytesFromDataInputStream(DataInputStream dis) throws IOException {
        // 使用 ByteArrayOutputStream 来收集所有读取的字节
        try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
            // 使用一个合适的缓冲区大小
            byte[] data = new byte[4096];
            int nRead;
            while ((nRead = dis.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            buffer.flush();
            return buffer.toByteArray();
        }
    }
}
