/*
 * Cordova TetherInfo Plugin
 *
 * TetherInfo plugin for Cordova/Phonegap
 * by Jonas Olmstead
 */

package se.easyserv.plugin;

import android.net.wifi.WifiManager;
import android.content.IntentFilter;
import android.content.Intent;
import android.content.Context;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import java.util.Set;
import android.util.Log;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;

public class TetherInfo extends CordovaPlugin implements ServiceListener {

    WifiManager.MulticastLock lock;
    private JmDNS publisher = null;
    private JmDNS browser = null;
    private String hostname = UUID.randomUUID().toString();
    private Map<String, CallbackContext> callbacks = new HashMap<String, CallbackContext>();

    public static final String ACTION_LISTIP = "listip";
    public static final String ACTION_CHECKUSB = "checkusb";

    /*@Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);

        WifiManager wifi = (WifiManager) this.cordova.getActivity().getSystemService(android.content.Context.WIFI_SERVICE);
        lock = wifi.createMulticastLock("ZeroConfPluginLock");
        lock.setReferenceCounted(true);
        lock.acquire();

        Log.v("ZeroConf", "Initialized");
    }*/

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {

        if (ACTION_LISTIP.equals(action)) {

            Log.d("TetherInfo", "ListIP ");

            String ips = getUSBThetheredIP();

            callbackContext.success(ips);

        } else if (ACTION_CHECKUSB.equals(action)) {

            Log.d("TetherInfo", "CheckUSB ");

            Context context = this.cordova.getActivity().getApplicationContext();
            //boolean bConnected = isUsbConnected(context);
            //boolean bConnected = isUsbConnected(context);

            callbackContext.success(isUsbConnected(context));

        } else {
            Log.e("TetherInfo", "Invalid action: " + action);
            callbackContext.error("Invalid action: " + action);
            return false;
        }

        return true;
    }

    public static JSONObject isUsbConnected(Context context) {

        Intent intent = context.registerReceiver(null, new IntentFilter("android.hardware.usb.action.USB_STATE"));
        //return intent.getExtras().getBoolean("connected");

        JSONObject json = new JSONObject();
        Bundle bundle = intent.getExtras();
        Set<String> keys = bundle.keySet();
        for (String key : keys) {
            try {
                // json.put(key, bundle.get(key)); see edit below
                json.put(key, JSONObject.wrap(bundle.get(key)));
            } catch(JSONException e) {
                //Handle exception here
            }
        }

        return json;
    }

    public static String getUSBThetheredIP() {

        BufferedReader bufferedReader = null;
        String ips="";

        try {
            bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"));

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                String[] splitted = line.split(" +");
                if (splitted != null && splitted.length >= 4) {
                    String ip = splitted[0];
                    String mac = splitted[3];
                    if (mac.matches("..:..:..:..:..:..")) {
                        if (mac.matches("00:00:00:00:00:00")) {
                            //Log.d("DEBUG", "Wrong:" + mac + ":" + ip);
                        } else {
                            //Log.d("DEBUG", "Correct:" + mac + ":" + ip);
                            ips = ips.length() == 0 ? ip : ips + "," + ip;
                            //break;
                        }
                    }
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ips;
    }


    @Override
    public void serviceResolved(ServiceEvent ev) {
        Log.d("TetherInfo", "Resolved");

    }

    @Override
    public void serviceRemoved(ServiceEvent ev) {
        Log.d("TetherInfo", "Removed");

    }

    @Override
    public void serviceAdded(ServiceEvent event) {
        Log.d("TetherInfo", "Added");

    }

}

@@ -1726,451 +1726,8 @@
 %22;%0A%0A
-    /*@Override%0A    public void initialize(CordovaInterface cordova, CordovaWebView webView) %7B%0A        super.initialize(cordova, webView);%0A%0A        WifiManager wifi = (WifiManager) this.cordova.getActivity().getSystemService(android.content.Context.WIFI_SERVICE);%0A        lock = wifi.createMulticastLock(%22ZeroConfPluginLock%22);%0A        lock.setReferenceCounted(true);%0A        lock.acquire();%0A%0A        Log.v(%22ZeroConf%22, %22Initialized%22);%0A    %7D*/%0A%0A
     
@@ -2197,34 +2197,32 @@
 ();%0A            
-//
 boolean bConnect
@@ -2235,75 +2235,14 @@
 sUsb
-Connected(context);%0A            //boolean bConnected = isUsbConnect
+Tether
 ed(c
@@ -2287,20 +2287,21 @@
 success(
-isUs
+%22%22 + 
 bConnect
@@ -2302,25 +2302,16 @@
 onnected
-(context)
 );%0A%0A    
@@ -2548,23 +2548,22 @@
 ct isUsb
-Connect
+Tether
 ed(Conte
@@ -2700,18 +2700,16 @@
         
-//
 return i
@@ -2742,461 +2742,17 @@
 an(%22
-connected%22);%0A%0A        JSONObject json = new JSONObject();%0A        Bundle bundle = intent.getExtras();%0A        Set%3CString%3E keys = bundle.keySet();%0A        for (String key : keys) %7B%0A            try %7B%0A                // json.put(key, bundle.get(key)); see edit below%0A                json.put(key, JSONObject.wrap(bundle.get(key)));%0A            %7D catch(JSONException e) %7B%0A                //Handle exception here%0A            %7D%0A        %7D%0A%0A        return json;
+rndis%22);%0A
 %0A   

add usb check