package org.kne.cloud.network.klalb;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class NetworkInterfaceManager {
    private List<NetworkInterface> networkInterfaceExcept = new ArrayList<>();
    private List<InetAddress> inetAddressesExcept = new ArrayList<>();

    public List<NetworkInterface> getNetworkInterfaceExcept() {
        return networkInterfaceExcept;
    }


    public List<InetAddress> getInetAddressesExcept() {
        return inetAddressesExcept;
    }

    public List<NetworkInterface> getAllAvaliableNetworkInterface() throws SocketException {
        List<NetworkInterface> interfaces = new ArrayList<NetworkInterface>();
        Enumeration<NetworkInterface> eu = NetworkInterface.getNetworkInterfaces();
        while (eu.hasMoreElements()) {
            NetworkInterface networkInterface = (NetworkInterface) eu.nextElement();

            if (networkInterface.getDisplayName()
                    .startsWith(CONST.KLALB_DECENTRALIZED_S_RV6_NETWORK)) {
                continue;
            }
            if (networkInterfaceExcept.contains(networkInterface)) {
                continue;
            }
            if (networkInterface.isUp()) {
                interfaces.add(networkInterface);
            }
        }
        return interfaces;
    }

    public List<InetAddress> getAllNetworkInterfaceAddress() throws SocketException {
        List<NetworkInterface> interfaces=getAllAvaliableNetworkInterface();
        List<InetAddress> addresses = new ArrayList<InetAddress>();
        for (NetworkInterface nif:interfaces){
            addresses.addAll(	getNetworkInterfaceAddress(nif));
        }
        return addresses;
    }

    public List<InetAddress> getNetworkInterfaceAddress(NetworkInterface networkInterface) throws SocketException {
        List<InetAddress> addresses = new ArrayList<InetAddress>();
        // System.out.println(networkInterface+" "+networkInterface.isUp());
        Enumeration<InetAddress> ei = networkInterface.getInetAddresses();
        while (ei.hasMoreElements()) {
            InetAddress inetAddress = (InetAddress) ei.nextElement();

            if (inetAddress.isLoopbackAddress()){
                continue;
            }
            if (inetAddressesExcept.contains( inetAddress)) {
                continue;
            }
            addresses.add(inetAddress);
        }

        return addresses;
    }

}
