/* 
 * Copyright 2011 by AVM GmbH <info@avm.de>
 *
 * This software contains free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License ("License") as 
 * published by the Free Software Foundation  (version 3 of the License). 
 * This software is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the copy of the 
 * License you received along with this software for more details.
 */

package de.avm.android.fritzapp.util;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;

import de.avm.android.fritzapp.gui.SettingsExtendedActivity;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

/**
 */
public class NetworkInterfaceHelper
{
	/**
	 * Gets addresses of network interfaces to use
	 * - all WLAN interfaces if WLAN connected
	 * - site local addresses if !SettingsExtendedActivity.isWlanOnly (VPN?)
	 * 
	 * @param context
	 * 		context to access preferences and system services
	 * @return
	 * 		list of addresses, might be empty 
	 * @throws IOException 
	 */
	public static ArrayList<InetAddress> getInetAddresses(Context context)
		throws IOException
	{
		NetworkInterface wifiInterface = null;
		WifiManager wifiManager = (WifiManager)context
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		if (wifiInfo != null)
		{
			int addr = wifiInfo.getIpAddress();
			if (addr != 0)
				wifiInterface = NetworkInterface.getByInetAddress(
						InetAddress.getByAddress(new byte[]
				    {
						(byte)(addr & 0xff),
						(byte)(addr >> 8 & 0xff),
						(byte)(addr >> 16 & 0xff),
						(byte)(addr >> 24 & 0xff)
					}));
		}

		ArrayList<InetAddress> result = new ArrayList<InetAddress>();
		addInetAdresses(result, wifiInterface, false);
		if (!SettingsExtendedActivity.isWlanOnly(context))
		{
			for (Enumeration<NetworkInterface> e = NetworkInterface
					.getNetworkInterfaces(); e.hasMoreElements(); )
			{
				NetworkInterface iface = e.nextElement();
				if ((wifiInterface == null) ||
						!wifiInterface.getName().equals(iface.getName()))
					addInetAdresses(result, iface, true);
			}
		}
		
		return result;
	}
	
	private static void addInetAdresses(ArrayList<InetAddress> list,
			NetworkInterface iface, boolean privateOnly)
		throws UnknownHostException
	{
		if (iface != null)
		{
			for (Enumeration<InetAddress> adrs = iface.getInetAddresses();
					adrs.hasMoreElements();)
			{
				InetAddress adr = adrs.nextElement();
				if (adr instanceof Inet4Address && !adr.isLoopbackAddress() &&
						(!privateOnly || InetAddressHelper
								.isSiteLocalAddress(adr.getHostAddress())))
					list.add(adr);
			}
		}
	}
}
