/* Copyright 2009 Palm, Inc.  All rights reserved. */

function AppAssistant(appController){
    this.appController = appController;
}

function StageAssistant(stageController){
    stageController.pushScene('test');
}

/*
	Constructor function for the test framework bringup scene assistant.
*/
function TestAssistant() {
}

/*
	Set up the widgets and menus.
*/
TestAssistant.prototype.setup = function() {
	var dividerFunc = function(testResult) {
		return testResult.suite;
	};
	
	this.testCollection = Mojo.Test.loadCollection(Mojo.appPath + "tests/all_tests.json");

	this.resultsModel = {listTitle: 'Waiting for Run', items:[]};

	this.controller.setupWidget('test-results', 
								{itemTemplate:'test/result', listTemplate:'test/testcontainer',
								dividerTemplate:'test/divider', dividerFunction: dividerFunc},
								this.resultsModel);

	this.controller.setupWidget(Mojo.viewMenu, undefined, {items: [{label: "Unit Test"}, {}]});

	this.controller.setupWidget(Mojo.commandMenu, undefined, 
			{items: [
				{label:"Run", command:'run'}
				]});
	var self=this;
	setTimeout(function(){self.runTests();},1000);

};

/*
	Handle the run menu command.
*/
TestAssistant.prototype.handleCommand = function handleCommand(commandEvent) {
	if(commandEvent.type == Mojo.Event.command) {
		if(commandEvent.command === 'run') {
			this.runTests();
		}
	}
};

/*
	Update the list widget that shows results.
*/
TestAssistant.prototype.updateResults = function updateResults(title, results) {
	this.resultsModel.listTitle = title || "Results";
	this.resultsModel.items = results || this.runner.results;
	this.controller.modelChanged(this.resultsModel);
};

/*
	Start the tests running.
*/
TestAssistant.prototype.runTests = function runTests() {
	/*
		Protecting this with a try/catch to aid in unit test framework development.
	*/
	Mojo.log('run');
	try {
		this.updateResults("Running", []);
		var tests = this.testCollection.collect(function(testSpec) {
			return Mojo.findConstructorFunction(testSpec.testFunction);
		});
		this.runner = new Mojo.Test.CollectionRunner(tests);
		this.runner.start(this.updateResults.bind(this));
	} catch (e) {
		var logMsg = "test runner failure: " + e.name + ': ';
		
		if (e.message) {
			logMsg = logMsg + e.message + " ";
		}
		
		if (e.sourceURL) {
			logMsg = logMsg + ', ' + e.sourceURL;
		}
		if (e.line) {
			logMsg = logMsg + ':' + e.line;
		}
		
		this.resultsModel.items = [{message: logMsg}];
		this.controller.modelChanged(this.resultsModel);
	}
};

