package hh.dejsem.hack;

import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.StrictMode;

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

import hh.dejsem.Act;
import hh.dejsem.net.NetUDP;

public class HackUDP extends Act {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(NetUDP.localAddr == null) {
			//new NetUDP(d);
			d.l(String.format("LAN broadcast=%s, myip=%s, hostname=%s",
					NetUDP.broadcastAddr.getHostAddress(), NetUDP.localAddr.getHostAddress(), getLocalHostName()));
		}

//		dgramReceive();
		dgramBcast("helemese nemelese");
	}

    String getLocalHostName() {
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		String hostname;
	    try  { hostname = InetAddress.getLocalHost().getHostName(); }
	    catch(UnknownHostException e) { hostname = null; }
	    return hostname;
	}

	InetAddress getLocalIp() {
		try {
			Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
//			if(en.hasMoreElements()) {
				for(; en.hasMoreElements(); ) {
					NetworkInterface i = en.nextElement();
					for(Enumeration<InetAddress> enumIpAddr = i.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
						InetAddress ia = enumIpAddr.nextElement();
						if( !ia.isLoopbackAddress() &&
							!ia.toString().substring(0, 0).getBytes().equals((byte) -128) &&
							Inet4Address.class.isInstance(ia))
							return ia;
					}
				}
//			}
		}
		catch(SocketException e) { d.abendMsg(e); }
		return null;
	}

	InetAddress getBroadcastAddress() {
		InetAddress broadcastAddr = null;
		try {
			DhcpInfo dhcp = ((WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE)).getDhcpInfo();
			if(dhcp != null && dhcp.ipAddress != 0) broadcastAddr = int2ia((dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask);
		}
		catch(Exception e) { d.abendMsg("get broadcast address", e); }
		return broadcastAddr;
	}

	void dgramReceive() { new HackDgrams(d, HackDgrams.REC).start(); }

	void dgramBcast(String msg) { new HackDgrams(d, HackDgrams.SEND, msg, NetUDP.broadcastAddr).start(); }

	void dgramClose() { new HackDgrams(d, HackDgrams.CLOSE).start(); }

	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);
    }
}
