package com.ningdatech.carapi.radar.client;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import cn.hutool.socket.SocketUtil;
import com.google.common.collect.Lists;
import com.ningdatech.carapi.radar.helper.RadarDataHelper;
import com.ningdatech.carapi.radar.model.entity.RadarData;
import com.ningdatech.carapi.radar.service.IRadarDataService;

import lombok.RequiredArgsConstructor;
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;
    private final RadarDataHelper radarDataHelper;

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

    @Override
    public void run() {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        // 获取输入流以读取雷达发送的数据
        try {
            // 从接入数据 开始 持续接收1分钟的数据 接收完成后 关闭连接
            // 设置1分钟后关闭连接
            executor.schedule(() -> {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    log.error("Error closing client socket: ", e);
                }
            }, 1, TimeUnit.MINUTES);

            InputStream dataInputStream = clientSocket.getInputStream();
            // 开启保活选项
            clientSocket.setKeepAlive(true);
            byte[] buffer = new byte[1024];
            int bytesRead;
            // 循环读取数据，直到Socket被关闭
            while (!clientSocket.isClosed() && (bytesRead = dataInputStream.read(buffer)) != -1) {
                // 处理读取到的数据
                String dataString = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
                log.info("Received: {}", dataString);
                RadarData radarData = new RadarData();
                radarData.setArmIp(radarIp);
                // 解析数据
                radarData.setCreateOn(LocalDateTime.now());
                radarData.setUpdateOn(LocalDateTime.now());
                radarDataService.save(radarData);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            // 关闭ScheduledExecutorService
            executor.shutdown();
            try {
                if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
            }
        }
    }

    private void processData(String dataString, RadarData radarData) {
        // 校验包头、包尾
    }
}
