package com.insa.app;

import javafx.application.Platform;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;

public final class Resources {
    public static final int clientPort = 8338;
    public static final int discoverPort = 44444;
    public static final int serverPort = 56765;
    static public final NetworkInterface getCommunicationInterface() throws Exception {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            if (iface.isLoopback() || !iface.isUp())
                // skip loopback and down interfaces
                continue;
            return iface;
        }
        throw new RuntimeException("Could not find a valid interface");
    }

    static public String getMyIp() throws Exception {
        String resultingIp = "noIP";
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            if (iface.isLoopback() || !iface.isUp())
                // skip loopback and down interfaces
                continue;
            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                resultingIp = address.getHostAddress();
            }
        }
        if (resultingIp == "noIP") {
            throw new RuntimeException("Failed to retrieve IP address : no interface is up");
        }
        return resultingIp;
    }

    static public final InetAddress getBroadcast() throws Exception{
        try {
            return InetAddress.getByName("255.255.255.255");
        }
        catch (Exception e) {
            Logger.getAnonymousLogger().log(Level.SEVERE, "Failed to find IP : " + e);
            Platform.exit();
            throw new RuntimeException("Failed to find IP " + e);
        }
    }

    static public final Optional<String> getPresenceServerIpFromArguments(List<String> parameters) {
        if (parameters.size() == 2 && parameters.get(0).equals("--presence-server")) {
            return Optional.of(parameters.get(1));
        }
        else {
            return Optional.empty();
        }
    }

}
