import cherrypy, sys, model
try:
	from cStringIO import StringIO
except:
	from StringIO import StringIO

page = """<html><body>

<script type="text/javascript">
function entsub(e) {
	var key;
	if(window.event)
		key = window.event.keyCode;	//IE
	else
		key = e.which;	//firefox

	if(key == 13)
		ajaxFunction();
}

function ajaxFunction() {
	var xmlhttp;
	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("Your browser does not support XMLHTTP!");
	}

	xmlhttp.onreadystatechange=function() {
		if(xmlhttp.readyState==4) {
			var txt = document.createTextNode(xmlhttp.responseText);
			document.getElementById('content').appendChild(txt);
			document.myForm.text.value = '';
			window.scrollBy(0, 500);
		}
	}

	var b = document.createElement('b');
	var txt = document.createTextNode("Parent: " + document.myForm.text.value + '\\n');
	b.appendChild(txt);
	document.getElementById('content').appendChild(b);

	xmlhttp.open("GET","runmodel?text=" + document.myForm.text.value, true);
	xmlhttp.send(null);
}
</script>

<div>
<pre>
Child dialogue simulator. Enter parent utterance.

[Some suggestions, which are not in the corpus:
 - "can you catch the ball ?" (simple combination of two utterances)
 - "where lives birdie ?", (stumbles on the right interpretation)
 - "that's a ball", (followed by)
 - "can you throw it ?" (it is related to ball)
 - "what does a duckie say ?"]

Utterances in corpus (utterances composed of these words should work):

%s
</pre>

<p>Distilled lexicon:</p>

<tt>%s</tt>

<p>Words in corpus:</p>

<tt>%s</tt>

<pre id=content>

</pre>
</div>

<form name="myForm" onSubmit="return false;">
Talk to me:
<input type="text" name="text" onKeyPress="return entsub(event)" />
<input type="button" value="speak" onClick="javascript:ajaxFunction();" />
<br />
</form>
</body></html>""" % ("\n".join(
			"".join((repr(a),
				' '*(30-len(a)),
				': ', repr(b))) for (a,b) in model.getexemplars().items()),
			" ".join(sorted(model.inferlexicon(model.getexemplars()).keys())),
			" ".join(sorted(set(' '.join(model.getexemplars()).split()))))

class GeneratorDemo:
	@cherrypy.expose
	def index(self, text=None):
		if text:
			return "<html><body><pre>%s</pre></body></html>" % self.runmodel(text)
		return page


	@cherrypy.expose
	def runmodel(self, text = None, d=model.dialogue(), init=[False]):
		# initialize d, but only once:
		if not init[0]:
			try:
				d.next()
				d.send('test')
			except:
				d=model.dialogue()
				d.next()
				d.send('test')
				init = [True]
		if text:
			# capture standard output in a string:
			sys.stdout = StringIO()
			reply = d.send(text)
			return sys.stdout.getvalue() + 'Child:  ' + reply + '\n'
			sys.stdout = sys.__stdout__

cherrypy.tree.mount(GeneratorDemo())

if __name__ == '__main__':
	import os.path
	cherrypy.config.update(os.path.join(os.path.dirname(__file__), 'tutorial.conf'))
	#cherrypy.server.quickstart()
	cherrypy.engine.start()
