#include "jsc_gui.h"

JSReturnType functionAlert(ExecState* exec) {
	String txt;
	for (unsigned i = 0; i < exec->argumentCount(); ++i)
		txt+=String(i?" ":"")+exec->argument(i).toString(exec).UTF8String().data();
	PromptOK(txt);
	return JSValue::encode(jsUndefined());
}

JSReturnType functionQuery(ExecState* exec) {
	WithQueryLayout<TopWindow> dlg;
	CtrlLayoutOKCancel(dlg, "Query");
	dlg.lbl = exec->argument(0).toString(exec).UTF8String().data();
	dlg.text<<="";
	if(dlg.Execute() == IDOK) {
		return JSValue::encode(jsString(exec, UString( AsString(~(dlg.text)) )));
	}
	return JSValue::encode(jsUndefined());
}

jsc_gui::jsc_gui(){
	CtrlLayout(*this, "Window title");
	Sizeable().Title("JavaScript interpreter");
	script.Highlight(CodeEditor::HIGHLIGHT_JAVA); // Java should be close enough to JavaScript :-)
	script<<="function hello(){\n"
	         "  name=query(\"Hello, what's your name?\")\n"
	         "  alert(\"Hello \"+name+\"!\")\n"
	         "}\n"
	         "hello()";
	exec<<=THISBACK(Exec);
	js.AddNativeFunction("query",functionQuery);
	js.AddNativeFunction("alert",functionAlert);
}

void jsc_gui::Exec(){
	String result;
	if(!js.Execute(~script,result))
		Exclamation("Error: "+result);
}

GUI_APP_MAIN{
	jsc_gui().Run();
}

