package com.pdi.hybridge;

import java.util.Observable;

import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.webkit.WebView;

import com.pdi.hybridge.HybridgeConst.Event;

public class HybridgeBroadcaster extends Observable {
	
	private static HybridgeBroadcaster instance;
	
	private boolean isInitialized = false;
	
	private final String TAG = "HybridgeBroadcaster";
	
	public HybridgeBroadcaster () {
	}

    public static HybridgeBroadcaster getInstance () {
        if (instance == null) {
            instance = new HybridgeBroadcaster();
        }
        return instance;
    }

    public void initJs (WebView view, JSONArray actions, JSONArray events) {
        runJsInWebView(view, "window.HybridgeGlobal || function () {" +
                "window.HybridgeGlobal = {" +
                "  isReady : true" +
                ", version : " + HybridgeConst.VERSION +
                ", actions : " + actions.toString() +
                ", events : " + events.toString() +
                "};" +
                "window.$ && $('#hybridgeTrigger').toggleClass('switch');" +
                "}()"
                );
        isInitialized = true;
    }

	public void firePause (WebView view) {
		HybridgeConst.Event event = HybridgeConst.Event.PAUSE;
		notifyObservers(event);
		fireJavascriptEvent(view, event, null);
	}
	
	public void fireResume (WebView view) {
		HybridgeConst.Event event = HybridgeConst.Event.RESUME;
		notifyObservers(event);
		fireJavascriptEvent(view, event, null);
	}
	
	public void fireMessage (WebView view, JSONObject data) {
		HybridgeConst.Event event = HybridgeConst.Event.MESSAGE;
		notifyObservers(event);
		fireJavascriptEvent(view, event, data);
	}
	
    public void fireReady (WebView view, JSONObject data) {
        HybridgeConst.Event event = HybridgeConst.Event.READY;
        notifyObservers(event);
        fireJavascriptEvent(view, event, data);
    }
	
	public void fireJavascriptEvent (WebView view, Event event, JSONObject data) {
		if (isInitialized) {
			String json = data != null ? data.toString() : "{}";
			StringBuffer js = new StringBuffer("HybridgeGlobal.fireEvent(\"");
			js.append(event.getJsName()).append("\",").append(json).append(");");
			runJsInWebView(view, js.toString());
		}
	}

	public void runJsInWebView (final WebView view, final String js) {
	    new Handler(Looper.getMainLooper()).post(
	            new Runnable() {
	                @Override
	                public void run() {
	                    view.loadUrl("javascript:(function(){" + js + "})()");
	                }
	            });
	}
	
	public void updateState (JSONObject data) {
		this.setChanged();
		this.notifyObservers(data);
		Log.d(TAG, data.toString());
	}
	
}

@@ -37,26 +37,79 @@
 va.util.
-Observable
+HashMap;%0Aimport java.util.Observable;%0Aimport java.util.Observer
 ;%0A%0Aimpor
@@ -159,16 +159,45 @@
 bject;%0A%0A
+import android.os.AsyncTask;%0A
 import a
@@ -549,38 +549,197 @@
 %09%0A%09p
-ublic HybridgeBroadcaster () %7B
+rivate HashMap%3CInteger, AsyncTask%3CJSONObject, Void, JSONObject%3E%3E currents;%0A%09%0A%09public HybridgeBroadcaster () %7B%0A%09    currents =  new HashMap%3CInteger, AsyncTask%3CJSONObject,Void,JSONObject%3E%3E();
 %0A%09%7D%0A
@@ -3043,10 +3043,960 @@
 );%0A%09%7D%0A%09%0A
+%09@SuppressWarnings(%22unchecked%22)%0A%09@Override%0A    public void addObserver(Observer observer) %7B%0A%09    super.addObserver(observer);%0A%09    Class%3C?%3E clazz = observer.getClass().getSuperclass();%0A%09    if(clazz != null && clazz == android.os.AsyncTask.class) %7B%0A%09        int hashCode = observer.hashCode();%0A%09        AsyncTask%3CJSONObject, Void, JSONObject%3E current = currents.get(hashCode); %0A%09        if(current != null) %7B%0A%09            if(current.cancel(true)) %7B%0A%09                currents.remove(hashCode);%0A%09            %7D%0A%09        %7D%0A%09        currents.put(hashCode, (AsyncTask%3CJSONObject, Void, JSONObject%3E) observer);%0A%09    %7D%0A%09%7D%0A%09%0A%09@Override%0A    public void deleteObserver(Observer observer) %7B%0A%09    super.deleteObserver(observer);%0A        Class%3C?%3E clazz = observer.getClass().getSuperclass();%0A        if(clazz != null && clazz == android.os.AsyncTask.class) %7B%0A            int hashCode = observer.hashCode();%0A            currents.remove(hashCode);%0A        %7D%09    %0A%09%7D%0A
 %7D%0A

EDIT implement thread control