using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Edge.Core.Processor.Communicator
{
    public class TcpServer
    {
        private TcpListener _listener;
        private string _localIp;
        private int _port;

        public TcpServer(string localIp, int port)
        {
            _localIp = localIp;
            _port = port;
            _listener = new TcpListener(IPAddress.Parse(_localIp), _port);
        }

        public async Task StartAsync()
        {
            _listener.Start();
            Console.WriteLine("Server started. Listening for connections...");

            while (true)
            {
                // 异步等待客户端连接
                TcpClient client = await _listener.AcceptTcpClientAsync();
                IPEndPoint clientEndPoint = (IPEndPoint)client.Client.RemoteEndPoint;
                string clientIp = clientEndPoint.Address.ToString();
                int clientPort = clientEndPoint.Port;
                Console.WriteLine($"Client connected: {clientIp}:{clientPort}");

                // 处理客户端连接
                Task.Run(() => HandleClient(client, clientIp, clientPort));
            }
        }

        private async Task HandleClient(TcpClient client, string clientIp, int clientPort)
        {
            using (client)
            {
                NetworkStream stream = client.GetStream();
                byte[] buffer = new byte[1024];

                while (true)
                {
                    try
                    {
                        // 从客户端读取数据
                        int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
                        if (bytesRead == 0)
                        {
                            // 客户端断开连接
                            break;
                        }

                        // 将接收到的数据转换为字符串
                        string data = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                        Console.WriteLine($"Received from {clientIp}:{clientPort}: {data}");

                        // 回应客户端
                        string response = "Message received: " + data;
                        byte[] responseBytes = Encoding.UTF8.GetBytes(response);
                        await stream.WriteAsync(responseBytes, 0, responseBytes.Length);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Error handling client {clientIp}:{clientPort}: {ex.Message}");
                        break;
                    }
                }

                Console.WriteLine($"Client disconnected: {clientIp}:{clientPort}");
            }
        }

        public void Stop()
        {
            _listener.Stop();
            Console.WriteLine("Server stopped.");
        }
    }
}
