package com.pig4cloud.pig.statistics.socket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * TCP服务器主类，负责监听端口和管理客户端连接
 */
@Slf4j
@Component
public class TcpServer {
	@Value("${tcp.server.port}")
	private int port;

	private ServerSocket serverSocket;
	private boolean isRunning;
	private final ClientHandlerFactory clientHandlerFactory;

	public TcpServer() {
		this.clientHandlerFactory = new ClientHandlerFactory();
	}

	/**
	 * 启动服务器，Spring初始化后自动调用
	 */
	@PostConstruct
	public void start() throws IOException {
		serverSocket = new ServerSocket(port);
		isRunning = true;
		log.info("TCP服务器已启动，监听端口: {}", port);

		// 启动接受客户端连接的线程
		new Thread(this::acceptConnections, "ConnectionAcceptor").start();
	}

	/**
	 * 接受客户端连接的循环
	 */
	private void acceptConnections() {
		while (isRunning) {
			try {
				// 接受客户端连接
				Socket clientSocket = serverSocket.accept();
				log.info("新客户端连接: {}", clientSocket.getInetAddress().getHostAddress());

				// 创建并启动客户端处理器
				ClientHandler clientHandler = clientHandlerFactory.createClientHandler(clientSocket);
				new Thread(clientHandler, "ClientHandler-" + clientSocket.getInetAddress()).start();
			} catch (IOException e) {
				if (isRunning) {
					log.error("接受客户端连接错误: {}", e.getMessage(), e);
				} else {
					log.info("服务器已停止，不再接受新连接");
				}
			}
		}
	}

	/**
	 * 停止服务器，Spring销毁前自动调用
	 */
	@PreDestroy
	public void stop() {
		isRunning = false;
		try {
			if (serverSocket != null) {
				serverSocket.close();
			}
			log.info("TCP服务器已停止");
		} catch (IOException e) {
			log.error("停止服务器错误: {}", e.getMessage(), e);
		}
	}
}
    