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



namespace EasyTemplate.Service
{





    public class UdpServerService : IHostedService
    {
        private UdpClient udpServer;
        private IPEndPoint endPoint;
        private CancellationTokenSource cancellationTokenSource;
        public event Action<string> OnMessageReceived;

        public string data;

        public UdpServerService()
        {
        }
        private void DoWork(object state)
        {
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            cancellationTokenSource = new CancellationTokenSource();
            endPoint = new IPEndPoint(IPAddress.Any, 10000);
            udpServer = new UdpClient(endPoint);

            _ = Task.Run(async () =>
            {
                while (!cancellationTokenSource.Token.IsCancellationRequested)
                {
                    try
                    {
                        UdpReceiveResult result = await udpServer.ReceiveAsync();
                        string message = Encoding.UTF8.GetString(result.Buffer);
                        data = message;
                        OnMessageReceived?.Invoke($"Received: {message} from {result.RemoteEndPoint}");

                        // Echo back
                        byte[] responseData = Encoding.UTF8.GetBytes("Echo: " + message);
                        await udpServer.SendAsync(responseData, responseData.Length, result.RemoteEndPoint);
                    }
                    catch (ObjectDisposedException)
                    {
                        break;
                    }
                    catch (Exception ex)
                    {
                        OnMessageReceived?.Invoke($"Error: {ex.Message}");
                    }
                }
            }, cancellationTokenSource.Token);

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            cancellationTokenSource?.Cancel();
            udpServer?.Close();
            return Task.CompletedTask;
        }
    }
}



