package com.ionic.keyboard;

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.Status;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.InputMethodManager;

public class IonicKeyboard extends CordovaPlugin{

    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);

        //calculate density-independent pixels (dp)
        //http://developer.android.com/guide/practices/screens_support.html
        DisplayMetrics dm = new DisplayMetrics();
        cordova.getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        final float density = dm.density;

        final CordovaWebView appView = webView;

        //http://stackoverflow.com/a/4737265/1091751 detect if keyboard is showing
        final View rootView = cordova.getActivity().getWindow().getDecorView().findViewById(android.R.id.content).getRootView();
        OnGlobalLayoutListener list = new OnGlobalLayoutListener() {
            int previousHeightDiff = 0;
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                //r will be populated with the coordinates of your view that area still visible.
                rootView.getWindowVisibleDisplayFrame(r);

                int heightDiff = rootView.getRootView().getHeight() - (r.bottom - r.top);
                int pixelHeightDiff = (int)(heightDiff / density);
                if (pixelHeightDiff > 100 && pixelHeightDiff != previousHeightDiff) { // if more than 100 pixels, its probably a keyboard...
                    appView.sendJavascript("cordova.plugins.Keyboard.isVisible = true");
                    appView.sendJavascript("cordova.fireWindowEvent('native.keyboardshow', { 'keyboardHeight':" + Integer.toString(pixelHeightDiff)+"});");

                    //deprecated
                    appView.sendJavascript("cordova.fireWindowEvent('native.showkeyboard', { 'keyboardHeight':" + Integer.toString(pixelHeightDiff)+"});");
                }
                else if ( pixelHeightDiff != previousHeightDiff && ( previousHeightDiff - pixelHeightDiff ) > 100 ){
                    appView.sendJavascript("cordova.plugins.Keyboard.isVisible = false");
                    appView.sendJavascript("cordova.fireWindowEvent('native.keyboardhide')");

                    //deprecated
                    appView.sendJavascript("cordova.fireWindowEvent('native.hidekeyboard')");
                }
                previousHeightDiff = pixelHeightDiff;
             }
        };

        rootView.getViewTreeObserver().addOnGlobalLayoutListener(list);
    }

    public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
        if ("close".equals(action)) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    //http://stackoverflow.com/a/7696791/1091751
                    InputMethodManager inputManager = (InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    View v = cordova.getActivity().getCurrentFocus();

                    if (v == null) {
                        callbackContext.error("No current focus");
                    }
                    inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    callbackContext.success(); // Thread-safe.
                }
            });
            return true;
        }
        if ("show".equals(action)) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    ((InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
                    callbackContext.success(); // Thread-safe.
                }
            });
            return true;
        }
        return false;  // Returning false results in a "MethodNotFound" error.
    }


}


@@ -196,55 +196,8 @@
 ew;%0A
-import org.apache.cordova.PluginResult.Status;%0A
 impo
@@ -251,16 +251,53 @@
 ption;%0A%0A
+import android.annotation.TargetApi;%0A
 import a
@@ -350,16 +350,41 @@
 s.Rect;%0A
+import android.os.Build;%0A
 import a
@@ -599,18 +599,20 @@
 vaPlugin
+ 
 %7B%0A
+%09
 %0A    pub
@@ -1033,25 +1033,24 @@
 ensity;%0A
-%0A
         
 final Co
@@ -1045,48 +1045,8 @@
     
-final CordovaWebView appView = webView;%0A
 %0A   
@@ -1778,16 +1778,33 @@
 nsity);%0A
+                %0A
         
@@ -1952,32 +1952,24 @@
             
-appView.
 sendJavascri
@@ -2033,32 +2033,24 @@
             
-appView.
 sendJavascri
@@ -2215,32 +2215,24 @@
             
-appView.
 sendJavascri
@@ -2498,32 +2498,24 @@
             
-appView.
 sendJavascri
@@ -2580,32 +2580,24 @@
             
-appView.
 sendJavascri
@@ -2708,16 +2708,8 @@
     
-appView.
 send
@@ -4379,12 +4379,551 @@
 %0A    %7D%0A%0A
+%09@TargetApi(Build.VERSION_CODES.KITKAT)%0A%09private void sendJavascript(final String javascript) %7B%0A%0A%09%09webView.post(new Runnable() %7B%0A%09%09    @Override%0A%09%09    public void run() %7B%0A%09%09%09%09// See: https://github.com/GoogleChrome/chromium-webview-samples/blob/master/jsinterface-example/src/com/google/chrome/android/example/jsinterface/MainActivity.java%0A%09%09%09%09if (Build.VERSION.SDK_INT %3E= Build.VERSION_CODES.KITKAT) %7B%0A%09%09%09%09%09webView.evaluateJavascript(javascript, null);%0A%09%09%09%09%7D else %7B%0A%09%09%09%09%09webView.loadUrl(%22javascript:%22 + javascript);%0A%09%09%09%09%7D%0A%09%09    %7D%0A%09%09%7D);%0A%09%7D
 %0A%7D%0A%0A

Remove depreciated call to sendJavaScript for more recent method