using InnovEnergy.App.Middleware;
using System;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text;
using InnovEnergy.Lib.Utils;

internal class Program
{
    public static readonly object SharedDataLock = new object();
    
    public static async Task Main(string[] args)
    {
        //For each installation id, we maintain a list of the connected clients
        var installationConnections = new Dictionary<int, InstallationInfo>();
        var installationsIds = new List<int> {1};
        var installationIps = new List<string> {"10.2.3.115"};
        var MAX_RETRANSMISSIONS = 2;
        
        RabbitMqConsumer.StartRabbitMqConsumer(installationConnections,SharedDataLock);
        
        UdpClient udpClient = new UdpClient();
        udpClient.Client.ReceiveTimeout = 2000;
        int port = 9000;
        //Send a message to each installation and tell it to subscribe to the queue
        for (int i = 0; i < installationsIds.Count; i++)
        {
            using (udpClient)
            {
                //Try at most MAX_RETRANSMISSIONS times to reach an installation.
                for (int j = 0; j < MAX_RETRANSMISSIONS; j++)
                {
                    string message = "This is a message from RabbitMQ server, you can subscribe to the RabbitMQ queue";
                    byte[] data = Encoding.UTF8.GetBytes(message);
                    udpClient.Send(data, data.Length, installationIps[i], port);

                    Console.WriteLine($"Sent UDP message to {installationIps[i]}:{port}: {message}");
                    IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(installationIps[i]), port);
                    
                    try
                    {
                        byte[] replyData = udpClient.Receive(ref remoteEndPoint);
                        string replyMessage = Encoding.UTF8.GetString(replyData);
                        Console.WriteLine("Received message from installation " + installationsIds[i]);
                        break;
                    }
                    catch (SocketException ex)
                    {
                        if (ex.SocketErrorCode == SocketError.TimedOut)
                        {
                            Console.WriteLine("Timed out waiting for a response. Retry...");
                        }
                        else
                        {
                            Console.WriteLine("Error: " + ex.Message);
                        }
                    }
                }
            }
        }
        
        Console.WriteLine("WebSocket server is running. Press Enter to exit.");
        await WebSocketListener.StartServerAsync(installationConnections,SharedDataLock);
    }
}