package org.saiku.web.export;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.saiku.web.rest.objects.resultset.QueryResult;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JSConverter {

	public static String convertToHtml(QueryResult qr, boolean wrapcontent) throws IOException {
		ObjectMapper om = new ObjectMapper();
		StringWriter sw = new StringWriter();
		Context context = Context.enter();
		Scriptable globalScope = context.initStandardObjects();
		Reader underscoreReader = new InputStreamReader(JSConverter.class.getResourceAsStream("underscore.js"));
		context.evaluateReader(globalScope, underscoreReader, "underscore.js", 1, null);
		Reader srReader = new InputStreamReader(JSConverter.class.getResourceAsStream("SaikuRenderer.js"));
		context.evaluateReader(globalScope, srReader, "SaikuRenderer.js", 1, null);
		Reader strReader = new InputStreamReader(JSConverter.class.getResourceAsStream("SaikuTableRenderer.js"));
		context.evaluateReader(globalScope, strReader, "SaikuTableRenderer.js", 1, null);

		String data = om.writeValueAsString(qr);
		Object wrappedQr = Context.javaToJS(data, globalScope);
		ScriptableObject.putProperty(globalScope, "data", wrappedQr);

		Object wrappedOut = Context.javaToJS(sw, globalScope);
		ScriptableObject.putProperty(globalScope, "out", wrappedOut);

		String code = "eval('var cellset = ' + data); \nvar renderer = new SaikuTableRenderer(); \nvar html = renderer.render(cellset, { wrapContent : " + wrapcontent + " }); out.write(html);";

		context.evaluateString(globalScope, code, "<mem>", 1, null);
		Context.exit();

		String content = sw.toString();
		return content;

	}

	public static String convertToHtml(QueryResult qr) throws IOException {
		return convertToHtml(qr, false);
	}

}

@@ -501,16 +501,74 @@
 ption %7B%0A
+%09%09if (qr.getCellset() == null) %7B%0A%09%09%09return %22No Data%22;%0A%09%09%7D%0A
 %09%09Object
@@ -1631,24 +1631,32 @@
  + data); %5Cn
+%22%0A%09%09 + %22
 var renderer
@@ -1686,16 +1686,24 @@
 er(); %5Cn
+%22%0A%09%09 + %22
 var html
@@ -1774,24 +1774,79 @@
 %7D); 
-out.write(html);
+%5Cn%22%0A%09%09 + %22if (html) %7B out.write(html); %7D else %7B out.write('No Data'); %7D
 %22;%0A%0A

fix empty result issue