package hu.dpal.phonegap.plugins;

import java.util.Stack;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.widget.ProgressBar;

public class SpinnerDialog extends CordovaPlugin {

	public Stack<ProgressDialog> spinnerDialogStack = new Stack<ProgressDialog>();

	public SpinnerDialog() {
	}

	public boolean execute(String action, JSONArray args,
			final CallbackContext callbackContext) throws JSONException {
		if (action.equals("show")) {

			final String title = args.getString(0) == "null" ? null : args
					.getString(0);
			final String message = args.getString(1) == "null" ? null : args
					.getString(1);
            final boolean isFixed = args.getBoolean(2);
                
			final CordovaInterface cordova = this.cordova;
			Runnable runnable = new Runnable() {
				public void run() {
					
					DialogInterface.OnCancelListener onCancelListener = new DialogInterface.OnCancelListener() {
						public void onCancel(DialogInterface dialog) {
							if (!isFixed) {
								while (!SpinnerDialog.this.spinnerDialogStack.empty()) {
									SpinnerDialog.this.spinnerDialogStack.pop().dismiss();
									callbackContext.success();
								}
							}
						}
					};
					
					ProgressDialog dialog;
					if (isFixed) {
						dialog = CallbackProgressDialog.show(cordova.getActivity(), title, message, true, false, null, callbackContext);
					} else {
						dialog = ProgressDialog.show(cordova.getActivity(), title, message, true, true, onCancelListener);
					}
					
					if (title == null && message == null) {
						dialog.setContentView(new ProgressBar(cordova.getActivity()));
					}
					
					SpinnerDialog.this.spinnerDialogStack.push(dialog);

				}
			};
			this.cordova.getActivity().runOnUiThread(runnable);

		} else if (action.equals("hide")) {

			Runnable runnable = new Runnable() {
				public void run() {

					if (!SpinnerDialog.this.spinnerDialogStack.empty()) {
						SpinnerDialog.this.spinnerDialogStack.pop().dismiss();
					}

				}
			};
			this.cordova.getActivity().runOnUiThread(runnable);

		}
		return true;
	}

}
@@ -568,20 +568,17 @@
 ay args,
-%0A%09%09%09
+ 
 final Ca
@@ -683,24 +683,38 @@
 ing title = 
+%22null%22.equals(
 args.getStri
@@ -718,26 +718,17 @@
 tring(0)
- == %22null%22
+)
  ? null 
@@ -725,38 +725,32 @@
 )) ? null : args
-%0A%09%09%09%09%09
 .getString(0);%0A%09
@@ -774,16 +774,30 @@
 ssage = 
+%22null%22.equals(
 args.get
@@ -809,18 +809,9 @@
 g(1)
- == %22null%22
+)
  ? n
@@ -820,22 +820,16 @@
 l : args
-%0A%09%09%09%09%09
 .getStri
@@ -835,28 +835,19 @@
 ing(1);%0A
-            
+%09%09%09
 final bo
@@ -2275,8 +2275,9 @@
 e;%0A%09%7D%0A%0A%7D
+%0A

String comparison: equals vs ==