import tmpl;
import dom;
class ScriptToD
{
	static char[] htmlToD(char[] name, char[] html){
		TmplParser p = new TmplParser();
		Dom tmpl = p.parse(html);
		ScriptDom script = ScriptDom.tmplToScript(tmpl);
		return convert(name,script);
	}
	static char[] convert(char[] name, ScriptDom script){
		char[] prog;
		prog ~=		"import tmpl;\n"
					"import dom;\n"
					"class "~name~":ScriptDom{\n"
					"	static this(){\n"
					"		TmplDom.classHash[\""~name~"\"]=new test(Dom.BLOCK,\"script\");\n"
					"	}\n"
					"	ScriptDom newScript(){\n"
					"		return new test(Dom.BLOCK,\"script\");\n"
					"	}\n"
					"	this(byte type,char[] value){\n"
					"		super(type,value);\n"
					"		pos=0;\n"
					"	}\n"
					"	void run(){\n"
					"		while(true){\n"
					"			switch(pos){\n";
		for(int i=0;i<script.array.length;i++){
			Dom d=script.array[i];
			if(d.value=="text"){
				prog ~=
					"			case "~std.string.toString(i)~":print(\""~ script.array[i].getAttr("v") ~"\");pos++;\n";
			}else
			if(d.value=="var"){
				prog ~=
					"			case "~std.string.toString(i)~":\n"
					"				if(!("\"~script.array[i].getAttr("v")~"\" in currentData.attr)){\n"
					"					if(mode == OUTPUT){\n"
					"					throw(new Exception(\"not found program data &lt;"~script.array[i].getAttr("v")~"&gt; line=\\\""~script.array[i].getAttr("line")~"\\\" pos=\\\""~script.array[i].getAttr("pos")~"\\\"\"));\n"
					"					}\n"
					"					return;\n"
					"				}\n"
					"				print(currentData.attr[\""~script.array[i].getAttr("v")~"\"]);\n"
					"				pos++;\n";
			}else
			if(d.value=="next"){
				prog ~=
					"			case "~std.string.toString(i)~":pos="~script.array[i].getAttr("goto")~";break;\n";
			}else
			if(d.value=="end"){
				prog ~=
					"			case "~std.string.toString(i)~":return;\n";
			}else{
				prog ~= 
					"			// "~script.array[i].toString()~"\n";
			}
		}
		prog ~= 	"			}\n"
				 	"			pos++;\n"
					"		}\n"
					"	}\n"
					"}\n";
		return prog;
	}
}
version(SCRIPT2D_TEST){
import std.file;
void main()
{
	char[] d = ScriptToD.htmlToD("test","<html><$dt></html>");
	printf("%.*s\n",d);
}
}
