package com.ningdatech.carapi.radar.server;

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

import com.ningdatech.carapi.radar.client.RadarHandler;
import com.ningdatech.carapi.radar.helper.RadarDataHelper;
import com.ningdatech.carapi.radar.model.dto.RadarInfoDTO;
import com.ningdatech.carapi.radar.service.IRadarDataService;

import cn.hutool.socket.SocketUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @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;
    private final RadarDataHelper radarDataHelper;

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

    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())) {
                // 每个设备创建一个线程 建立一个Socket
                executorService.execute(() -> {
                    try (Socket socket = SocketUtil.connect(radarInfo.getRadarIp(), radarInfo.getRadarPort(),60000)){
                        log.info("ServerSocket started on port: {}", radarInfo.getRadarPort());
                        while (!Thread.currentThread().isInterrupted()) {
                            log.info("Connected to a radar on port: {}", radarInfo.getRadarPort());
                            RadarHandler task = new RadarHandler(socket, radarDataService, radarInfo.getRadarIp(),radarDataHelper);
                            Thread thread = new Thread(task);
                            thread.start();
                        }
                    } catch (IOException e) {
                        log.error("Error occurred while client connection: ", e);
                    }
                });
            }
        }
    }
}
