import com.las3r.io.*;
import com.las3r.runtime.*;

public var rt:RT;
private var history:Array = [];
private var historyIdx:uint = 0;

[Embed(source="logo.lsr", mimeType="application/octet-stream")]
protected const LogoLsr:Class;
public var LOGO_LSR:String = (ByteArray(new LogoLsr).toString());

[Embed(source="help.html", mimeType="application/octet-stream")]
protected const HelpText:Class;
public var HELP_TEXT:String = (ByteArray(new HelpText).toString());

private function init():void {
	var stdout:OutputStream = new OutputStream( outputText );
	var stderr:OutputStream = new OutputStream( outputError );

	stage.quality = "medium";
	rt = new RT( stage, stdout, stderr );
	prevBtn.enabled = false;
	nextBtn.enabled = false;
	helpTextArea.htmlText = HELP_TEXT;
	(Var.internWithRoot(LispNamespace(rt.CURRENT_NS.get()), rt.sym1("logo"), logo, true))
	rt.evalStr( LOGO_LSR, showResult );
}

private function evaluate():void {
	rt.evalStr( "(try " + input.text + " (catch Object x x))", showResult );
}

private function showResult( val:* ):void {
	if( val is Error ) {
		outputError( rt.printToString(val) ); 
	} else {
		outputText( rt.printToString(val) ); 
	}
	history.push( {	input: input.text, output: output.text } );
	historyIdx = history.length - 1;
	prevBtn.enabled = historyIdx > 0;
	nextBtn.enabled = false;
}

private function historyGoto():void {
	input.text = history[historyIdx].input;
	output.text = history[historyIdx].output;
	prevBtn.enabled = historyIdx > 0;
	nextBtn.enabled = historyIdx < history.length - 1;
}

private function historyPrev():void {
	historyIdx--;
	historyGoto();
}

private function historyNext():void {
	historyIdx++;
	historyGoto();
}

private function outputText( str:String ):void {
	output.text = str + "\n";
}

private function outputError( str:String ):void {
	output.text = str + "\n";
}
