package com.pig4cloud.pig.statistics.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 客户端处理器，负责与单个客户端的所有数据交互
 */
public class ClientHandler implements Runnable {
    private final Socket clientSocket;
    private final ProtocolHandler protocolHandler;
    private final DataProcessor dataProcessor;

    public ClientHandler(Socket clientSocket, ProtocolHandler protocolHandler, DataProcessor dataProcessor) {
        this.clientSocket = clientSocket;
        this.protocolHandler = protocolHandler;
        this.dataProcessor = dataProcessor;
    }

    @Override
    public void run() {
        try (InputStream in = clientSocket.getInputStream();
             OutputStream out = clientSocket.getOutputStream()) {

            System.out.println("开始处理客户端数据: " + clientSocket.getInetAddress());
            
            // 循环处理客户端发送的数据包
            while (!clientSocket.isClosed()) {
                // 使用协议处理器解析数据包
                Packet packet = protocolHandler.readPacket(in);
                if (packet == null) {
                    break; // 连接关闭
                }
                
                // 处理数据包并获取响应
                byte[] responseData = dataProcessor.processData(packet.getType(), packet.getContent());
                
                // 发送响应
                protocolHandler.sendPacket(out, packet.getType(), responseData);
            }
        } catch (IOException e) {
            if (!clientSocket.isClosed()) {
                System.err.println("客户端处理错误: " + e.getMessage());
            }
        } finally {
            try {
                clientSocket.close();
                System.out.println("客户端连接已关闭: " + clientSocket.getInetAddress());
            } catch (IOException e) {
                System.err.println("关闭客户端连接错误: " + e.getMessage());
            }
        }
    }
}
    