package galatea.httpserver;

import galatea.dialog.InterpretedEvent;
import galatea.dialog.window.DialogManagerWindow;
import galatea.io.DeviceEvent;
import galatea.logger.Logger;
import galatea.util.StringHashArray;
import galatea.util.Util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;

public class HttpSession
	implements IHttpServerResponse, IHttpAsyncResponseListener {

	private IHttpResponseHtmlMaker htmlMaker_;
	private IHttpRequestResponder responder_;
	private Logger dbg = new Logger("HTTP");
	private ArrayList<HttpAsyncResponse> 
		httpAsyncResponses_ = new ArrayList<HttpAsyncResponse>();
	
	public HttpSession(IHttpResponseHtmlMaker o, IHttpRequestResponder r) {
		htmlMaker_ = o;
		responder_ = r;
		htmlMaker_.addHttpAsyncResponseListener(this);
	}

	public void enqueueHttpAsyncResponse(HttpAsyncResponse ev) {
		if (ev != null) {
			dbg.print("HttpServerResponse: update " + ev.toString());
			httpAsyncResponses_.add(ev);
		}
	}
	
	private void _dispHttpLog(String str) {
		dbg.print(str);
	}
	
	public String getResponse(String path) {
		_dispHttpLog("getResponse " + path);
		String path2 = path;
		try {
			path2 = URLDecoder.decode(path,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String response = "";
		StringHashArray ha = Util.getQueryFromRequest(path2);
		if (ha.getAsString("m").length() > 0) {
			String ev = ha.getAsString("e");
			if (ev.equals("listen")) {
				_dispHttpLog("listen (waiting)");
				while (httpAsyncResponses_.size() == 0) {
					try {
						Thread.sleep(1L);
					} catch (InterruptedException e) {}
				}
				HttpAsyncResponse de = (HttpAsyncResponse)httpAsyncResponses_.remove(0);
				response = de.getString();
				_dispHttpLog("asyncResponse " + response);
			} else {
				String arg = ha.getAsString("arg");
				String s = responder_.respondToHttpRequest(ha.getAsString("m"), ev, arg);
				_dispHttpLog("response " + s);
			}
		} else {
			String file = Util.getFileNameFromRequest(path2);
			if (file.equals("/")) {
				response = htmlMaker_.getDialogMonitorHtml();
				_dispHttpLog("doc " + file);
			}
			if (file.equals("/demo")) {
				response = htmlMaker_.getDemoAppHtml();
				_dispHttpLog("doc " + file);
			}
		}
		return response;
	}
	
	public static void main(String argv[]) {
		String html = "<html>${script}</html>\n<html>${script}</html>\n";
		StringHashArray replaces = new StringHashArray();
		replaces.put("${script}", "var $hoge = 100;");
		String res = Util.getDocumentFromTemplate(html, replaces);
		System.out.println(res);
	}

}
