package plugins.CENO.Client;

import java.net.MalformedURLException;
import java.util.concurrent.TimeUnit;

import net.minidev.json.JSONObject;
import plugins.CENO.CENOErrCode;
import plugins.CENO.CENOException;
import plugins.CENO.URLtoUSKTools;
import plugins.CENO.Client.ULPRManager.ulprStatus;
import freenet.client.FetchException;
import freenet.keys.FreenetURI;
import freenet.pluginmanager.PluginHTTPException;
import freenet.support.api.HTTPRequest;

public class LookupHandler extends AbstractCENOClientHandler {

	public String handleHTTPGet(HTTPRequest request) throws PluginHTTPException {
		boolean clientIsHtml = isClientHtml(request);

		String urlParam = request.getParam("url", "");
		if (urlParam.isEmpty()) {
			if (clientIsHtml) {
				return new CENOException(CENOErrCode.LCS_HANDLER_INVALID_URL).getMessage();
			}
			return returnErrorJSON(new CENOException(CENOErrCode.LCS_HANDLER_INVALID_URL));
		}

		try {
			urlParam = URLtoUSKTools.validateURL(urlParam);
		} catch (MalformedURLException e) {
			if (clientIsHtml) {
				return new CENOException(CENOErrCode.LCS_HANDLER_INVALID_URL).getMessage();
			}
			return returnErrorJSON(new CENOException(CENOErrCode.LCS_HANDLER_INVALID_URL));
		}

		FreenetURI calculatedUSK = null;
		try {
			calculatedUSK = URLtoUSKTools.computeUSKfromURL(urlParam, CENOClient.bridgeKey);
		} catch (Exception e) {
			return returnErrorJSON(new CENOException(CENOErrCode.LCS_HANDLER_INVALID_URL));
		}

		String localFetchResult = localCacheLookup(calculatedUSK);

		if (localFetchResult == null) {
			ulprStatus urlULPRStatus = ULPRManager.lookupULPR(urlParam);
			RequestSender.requestFromBridge(urlParam);
			if (urlULPRStatus == ulprStatus.failed) {
				if (clientIsHtml) {
					return printStaticHTMLReplace("Resources/requestedFromBridge.html", "[urlRequested]", urlParam);
				} else {
					JSONObject jsonResponse = new JSONObject();
					jsonResponse.put("complete", true);
					jsonResponse.put("found", "false");
					return jsonResponse.toJSONString();
				}
			} else {
				if (clientIsHtml) {
					return printStaticHTMLReplace("Resources/sentULPR.html", "[urlRequested]", urlParam);
				} else {
					JSONObject jsonResponse = new JSONObject();
					jsonResponse.put("complete", false);
					return jsonResponse.toJSONString();
				}
			}
		} else {
			if (clientIsHtml) {
				return localFetchResult;
			} else {
				JSONObject jsonResponse = new JSONObject();
				jsonResponse.put("complete", "true");
				jsonResponse.put("found", true);
				jsonResponse.put("bundle", localFetchResult);
				return jsonResponse.toJSONString();
			}
		}
	}

	private String localCacheLookup(FreenetURI calculatedUSK) {
		ClientGetSyncCallback getSyncCallback = new ClientGetSyncCallback();
		try {
			CENOClient.nodeInterface.localFetchURI(calculatedUSK, getSyncCallback);
		} catch (FetchException e) {
			e.printStackTrace();
		}
		String fetchResult = null;
		try {
			fetchResult = getSyncCallback.getResult(5L, TimeUnit.SECONDS);
		} catch (FetchException e) {
			fetchResult = localCacheLookup(e.newURI);
		}
		return fetchResult;
	}

	public String handleHTTPPost(HTTPRequest request)
			throws PluginHTTPException {
		return "LookupHandler: POST request received";
	}

}
@@ -137,16 +137,51 @@
 Object;%0A
+import net.minidev.json.JSONValue;%0A
 import p
@@ -205,16 +205,16 @@
 rrCode;%0A
-
 import p
@@ -1398,16 +1398,132 @@
 on e) %7B%0A
+%09%09%09if (clientIsHtml) %7B%0A%09%09%09%09return new CENOException(CENOErrCode.LCS_HANDLER_INVALID_URL).getMessage();%0A%09%09%09%7D else %7B%0A%09
 %09%09%09retur
@@ -1593,24 +1593,29 @@
 ALID_URL));%0A
+%09%09%09%7D%0A
 %09%09%7D%0A%0A%09%09Strin
@@ -2122,15 +2122,13 @@
 d%22, 
-%22
 false
-%22
 );%0A%09
@@ -2616,14 +2616,12 @@
 e%22, 
-%22
 true
-%22
 );%0A%09

Fix CC not being able to decode LCS response when a bundle is found