package javafx.webengine_debugger;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.WeakHashMap;

import javafx.scene.web.WebEngine;

/**
 * @author Riccardo Balbo
 */
public final class JavaFXWebEngineDebuggerFactory{
	public static Class<? extends Server>  DEFAULT_SERVER=ServerImpl.class;

	private static final  WeakHashMap<WebEngine,DebuggerReference> _REFERENCES=new WeakHashMap<WebEngine,DebuggerReference> ();
	
	/**
	 * @description This class will take care of stopping the debugger when its webengine is deallocated.
	 */
	private static class DebuggerReference{ 
		JavaFXWebEngineDebugger get;
		public DebuggerReference(JavaFXWebEngineDebugger debugger){
			this.get=debugger;
		}
		@Override
		public void finalize(){
			get.stop();			
		}
	}
	
	private static int getFreePort(){
		int port=0;
		try{
			ServerSocket s=new ServerSocket(0);
			port=s.getLocalPort();
			s.close();
		}catch(IOException e){
			e.printStackTrace();
		}
		return port;
	}
	
	public static synchronized JavaFXWebEngineDebugger create(Class<? extends Server> server_class,WebEngine engine,int port){
		try{			
			if(port==0)port=getFreePort();
			JavaFXWebEngineDebugger  debugger = new JavaFXWebEngineDebugger(server_class,engine,port);
			_REFERENCES.put(engine,new DebuggerReference(debugger));
			debugger.start();
			return debugger;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	public synchronized static int countInstances(){
		return _REFERENCES.size();
	}
	
	
	
	
// #######	
	public static synchronized JavaFXWebEngineDebugger create(WebEngine engine,int port){
		return create(DEFAULT_SERVER,engine,port);
	}

	public static synchronized void destroy(JavaFXWebEngineDebugger debugger){
		debugger.stop();
	}
// #######	


}

@@ -86,16 +86,71 @@
 Socket;%0A
+import java.util.Iterator;%0Aimport java.util.Map.Entry;%0A
 import j
@@ -1808,16 +1808,295 @@
 stop();%0A
+%09%09Iterator%3CEntry%3CWebEngine,DebuggerReference%3E%3E references_i=_REFERENCES.entrySet().iterator();%0A%09%09while(references_i.hasNext())%7B%0A%09%09%09Entry%3CWebEngine,DebuggerReference%3E entry=references_i.next();%0A%09%09%09if(entry.getValue().get==debugger)%7B%0A%09%09%09%09references_i.remove();%0A%09%09%09%09break;%0A%09%09%09%7D%0A%09%09%7D%0A
 %09%7D%0A// ##

Remove reference on destruction