package hh.dejsem.net;

import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;

import hh.dejsem.K;
import hh.dejsem.R;
import hh.dejsem.lastmile.LastMileMeterFrag;
import hh.lib.D;
import hh.lib.DF;

/**
 * Fragment for info about current network connectivity
 */
public class NetInfoFrag extends DF implements View.OnClickListener {

	static final String TITLETEXT = "net info";

	public static NetInfoFrag instantiate(D d) {
		NetInfoFrag nf = new NetInfoFrag();
		nf.d = d.klon(nf);
		return nf;
	}

	TextView myip;

	@Override
	public void onCreate(Bundle b) { super.onCreate(b); }

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		View netInfoView = inflater.inflate(R.layout.net_info, null);
		myip = (TextView)netInfoView.findViewById(R.id.myip);
		d.tv = (TextView)netInfoView.findViewById(R.id.tv);
		d.sc = (ScrollView)netInfoView.findViewById(R.id.sc);
		netInfoView.findViewById(R.id.throughput).setOnClickListener(this);
		printNetworkElements();
		return netInfoView;
	}

	@Override
	public void onResume() {
		super.onResume();
		K.title.setText(TITLETEXT).update();
	}

	@Override
	public void onClick(View v) {
		final FragmentManager fm = getActivity().getSupportFragmentManager();
		LastMileMeterFrag lastMile = (LastMileMeterFrag)fm.findFragmentByTag(K.LAST_MILE_TAG);
		if (lastMile == null) lastMile = LastMileMeterFrag.instantiate(d);
		fm.beginTransaction()
				.replace(R.id.panel, lastMile, K.LAST_MILE_TAG)
				.addToBackStack(null)
				.commitAllowingStateLoss();
	}

	void printNetworkElements() {
		try {
			Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
			if(en.hasMoreElements()) {
				for(;en.hasMoreElements();) {
					NetworkInterface i = en.nextElement();
					d.ttv(String.format("● %s: isLoopback=%b, isVirtual=%b, isPointToPoint=%b, isUp=%b",
							i.getDisplayName(), i.isLoopback(), i.isVirtual(), i.isPointToPoint(), i.isUp()));
					for(InterfaceAddress ifa : i.getInterfaceAddresses())
						d.ttv(String.format("● %s: iaddr=%s", i.getDisplayName(), ifa.getAddress().getHostAddress()));
					for(Enumeration<InetAddress> enumIpAddr = i.getInetAddresses(); enumIpAddr.hasMoreElements();) {
						InetAddress ia = enumIpAddr.nextElement();
						if( !ia.isLoopbackAddress() &&
							!ia.toString().substring(0, 0).getBytes().equals((byte)0xFF) &&
							Inet4Address.class.isInstance(ia)
							) myip.setText(Html.fromHtml(String.format("myip=<font color=\"#%06x\">%s</font>",
								getResources().getColor(R.color.dir_name_color) - 0xff000000, ia.getHostAddress())), TextView.BufferType.SPANNABLE);
					}
					d.ttv("");
				}
				DhcpInfo dhcp = ((WifiManager)getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE)).getDhcpInfo();
				if(dhcp != null) {
					d.ttv(String.format("● dhcp.ipAddress=%s", int2ia(dhcp.ipAddress).getHostAddress()));
					d.ttv(String.format("● dhcp.netmask=%s", int2ia(dhcp.netmask).getHostAddress()));
					d.ttv(String.format("● dhcp.broadcast=%s", int2ia((dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask).getHostAddress()));
				}
				d.ttv("");
            }
			else d.ttv("no network elements present");
		} catch(Exception e) { d.abendMsg(e); }
	}

	InetAddress int2ia(int ia) throws UnknownHostException {
		byte[] quad = new byte[4];
		for(int k = 0; k < 4; k++) quad[k] = (byte)((ia >> k * 8) & 0xFF);
		return InetAddress.getByAddress(quad);
    }
}
