package lc.mecha.net;

import lc.mecha.util.StringAccumulatorV2;

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

/**
 * @author Alex Leigh
 * @since mk20 (TOKYO PROTOCOL)
 */
public class NetworkInterfaceUtil {

    /**
     * Return a {@link List} of all the network hardware addresses on this host, in {@link String} format. The order the
     * addresses are returned is undefined. The returned list is owned by the caller.
     *
     * @return The List of addresses.
     */
    public static List<String> getHardwareNetworkAddresses() throws SocketException {
        ArrayList<String> result = new ArrayList<>();
        Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();

        while (nics.hasMoreElements()) {
            NetworkInterface nic = nics.nextElement();
            if (nic.getHardwareAddress() != null)
                result.add(NetworkInterfaceUtil.formatMacAddress(nic.getHardwareAddress()));
        }
        return result;
    }


    /**
     * Format a network hardware address into a typical human-readable format.
     *
     * @param hardwareAddress The binary hardware address to convert.
     * @return The string-formatted hardware address.
     */
    public static String formatMacAddress(byte[] hardwareAddress) {
        StringAccumulatorV2 sa = new StringAccumulatorV2(":");
        for (byte address : hardwareAddress) {
            sa.push(String.format("%02X", address));
        }
        return sa.asString();
    }
}
