package com.ningdatech.carapi.radar.server;

import com.ningdatech.carapi.radar.client.RadarHandler;
import com.ningdatech.carapi.radar.model.dto.RadarInfoDTO;
import com.ningdatech.carapi.radar.service.IRadarDataService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.*;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author CMM
 * @author CMM
 * @date 2024/9/28 10:27
 * /
 * /**
 * @since 2024/09/28 10:27
 */
@Slf4j
public class MultiRadarServer {

    private final IRadarDataService radarDataService;
    private final ExecutorService executorService;

    public MultiRadarServer(IRadarDataService radarDataService,List<RadarInfoDTO> radarInfoList) {
        this.radarDataService = radarDataService;
        this.executorService = Executors.newFixedThreadPool(radarInfoList.size());
    }


    public void startServers(List<RadarInfoDTO> radarInfoList) {
        log.info("Radar server started. Waiting for connections...");
        for (RadarInfoDTO radarInfo : radarInfoList) {
            if (Objects.nonNull(radarInfo.getRadarIp()) && Objects.nonNull(radarInfo.getRadarPort())) {
                // 每个设备创建一个线程 建立一个ServerSocket
                executorService.execute(() -> {
                    try (ServerSocket serverSocket = new ServerSocket(radarInfo.getRadarPort(), 600, InetAddress.getByName(radarInfo.getRadarIp()))){
                        // 设置为0表示无限等待，可以根据需要设置超时时间
                        serverSocket.setSoTimeout(0);
                        log.info("ServerSocket started on port: {}", radarInfo.getRadarPort());
                        while (!Thread.currentThread().isInterrupted()) {
                            Socket clientSocket = serverSocket.accept();
                            //log.info("Connected to a radar on port: {}", radarInfo.getRadarPort());
                            RadarHandler task = new RadarHandler(clientSocket, radarDataService, radarInfo.getRadarIp());
                            Thread thread = new Thread(task);
                            thread.start();
                        }
                    } catch (IOException e) {
                        log.error("Error occurred while accepting client connection: ", e);
                    }
                });
                
            }
        }
    }
}
