using ConfigOperator;
using RealtimeData;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;

namespace AlarmInfoServerSim.Services;

public class SharedConfig : ISharedConfig
{
    private Hardwares _hardwares;
    private List<IPAddress> _iPAddress;
    private IPAddress? _selectedIPAddress;
    private int? _selectedPort;

    public SharedConfig()
    {
        string hardwaresPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Settings", "Hardwares");
        _hardwares = new();
        HardwareFileLoader hardwareFileLoader = new(_hardwares);
        if (!hardwareFileLoader.Load(hardwaresPath))
        {
            throw new InvalidOperationException("Failed to Load correct hardware configs!");
        }

        _iPAddress = new();
        foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
        {
            if (netInterface.OperationalStatus == OperationalStatus.Up)
            {
                foreach (var ipInfo in netInterface.GetIPProperties().UnicastAddresses)
                {
                    if (ipInfo.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        _iPAddress.Add(ipInfo.Address);
                    }
                }
            }
        }
    }

    public Hardwares Hardwares => _hardwares;

    public List<IPAddress> IPAddresses => _iPAddress;

    public IPAddress? SelectedIPAddress { get => _selectedIPAddress; set => _selectedIPAddress = value; }

    public int? SelectedPort { get => _selectedPort; set => _selectedPort = value; }
}
