/*
Talky - A modulable hub for programming language interpreters in JavaScript.
Copyright (c) 2009 Thomas Peri

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

// Good Parts plus Browser:
/*jslint
	white: true, undef: true, nomen: true, eqeqeq: true, plusplus: true,
	bitwise: true, regexp: true, onevar: true, newcap: true,
	browser: true
*/
/*global Clumpy, iFace */

/**
 * version 2009-11-18
 */
var Talky = {
	Hub: function (parts) {
		var self = this,
			
			// private instance variables
			error, interpreter,
			clumpy, modules, options,
			running, paused, count, callback,
			
			// private methods
			construct, update, changed, nothing, the_next,
			
			// public methods
			setOptions, getOptions, addModule, getModule, lookup,
			run, init, stop, pause, next, resume, async;
		
		
		// Private Methods	
		
		construct = function () {
			// passed in
			parts = parts || {};
			error = parts.error || nothing;
			interpreter = parts.interpreter;
			Talky.InterpreterIF.verify(interpreter, 'interpreter');
			
			// created here
			modules = {};
			clumpy = new Clumpy({
				between: update
			});

			// set options
			options = {
				clumpyDelay: 0,
				clumpyDuration: 25,
				clumpyManual: false,
				maxUpdatesPerClump: 1,
				ignoreMaxUpdatesPerClump: true
			};
			setOptions(parts.options || {});
			
			// give the hub to the interpreter
			interpreter.setHub(self);
		};
		
		nothing = function () {
		};
		
		update = function (flag) {
			var mod;
			for (mod in modules) {
				if (modules.hasOwnProperty(mod)) {
					if (modules[mod].changed()) {
						modules[mod].update();
					}
				}
			}
		};
		
		changed = function () {
			var mod;
			for (mod in modules) {
				if (modules.hasOwnProperty(mod)) {
					if (modules[mod].changed()) {
						return true;
					}
				}
			}
			return false;
		};
		
		
		// Public Methods

		setOptions = function (opt) {
			var number, bool;
			opt = opt || {};
			number = function (key) {
				if (typeof opt[key] !== 'undefined') {
					options[key] = Math.max(0, parseInt(opt[key], 10) || 0);
				}
			};
			bool = function (key) {
				if (typeof opt[key] !== 'undefined') {
					options[key] = opt[key] ? true : false;
				}
			};
			number('clumpyDelay');
			number('clumpyDuration');
			bool('clumpyManual');
			number('maxUpdatesPerClump');
			bool('ignoreMaxUpdatesPerClump');

			clumpy.setNow({
				delay: options.clumpyDelay,
				duration: options.clumpyDuration,
				manual: options.clumpyManual
			});
		};
		
		getOptions = function () {
			return {
				clumpyDelay: options.clumpyDelay,
				clumpyDuration: options.clumpyDuration,
				clumpyManual: options.clumpyManual,
				maxUpdatesPerClump: options.maxUpdatesPerClump,
				ignoreMaxUpdatesPerClump: options.ignoreMaxUpdatesPerClump
			};
		};
	
		addModule = function () {
			var i, mod;
			for (i = 0; i < arguments.length; i += 1) {
				mod = arguments[i];
				Talky.ModuleIF.verify(mod, 'Talky.addModule');
				if (modules.hasOwnProperty(mod.name)) {
					throw "module " + mod.name + " is already loaded.";
				}
				modules[mod.name] = mod;
				mod.setHub(self);
				mod.init();
			}
		};
		
		getModule = function (modName) {
			if (modules.hasOwnProperty(modName)) {
				return modules[modName];
			}
			return null;
		};
		
		lookup = function (memName, optModName) {
			var mod, modName;
			if (optModName) {
				modName = optModName;
				if (modules.hasOwnProperty(modName)) {
					mod = modules[modName];
					if (mod.talky.hasOwnProperty(memName)) {
						return mod.talky[memName];
					} else {
						return null;
						//throw 'member ' + memName + ' is not defined in module ' + modName;
					}
				} else {
					throw 'module ' + modName + ' is not loaded';
				}
			} else {
				for (modName in modules) {
					if (modules.hasOwnProperty(modName)) {
						mod = modules[modName];
						if (mod.talky.hasOwnProperty(memName)) {
							return mod.talky[memName];
						}
					}
				}
				return null;
				//throw memName + " doesn't exist.";
			}
		};

		the_next = function () {
			var proceed;
		
			try {
				proceed = interpreter.next();
			} catch (e) {
				error(e);
				proceed = false;
			}
			
			// At this point, interpreter.next() might have called 
			// async(), but it's ok to finish the rest of this clump,
			// because the asynchronous operation is just enqueued to happen
			// after this one's over.  The clumpy.interrupt() is redundant
			// in that case, but harmless.
			
			if (proceed) {
				if (changed()) {
					count += 1;
				}
				if (!options.ignoreMaxUpdatesPerClump && 
					count >= options.maxUpdatesPerClump
				) {
					count = 0;
					clumpy.interrupt();
				}
			} else {
				stop();
			}
		};
		
		run = function (code, cb) {
			if (running) {
				return false;
			}
			running = true;
			callback = cb;
			
			try {
				interpreter.parse(code);
			} catch (e) {
				error(e);
			}

			count = 0;
			clumpy.while_loop(
				function () {
					return true;
				},
				the_next
			);

			return true;
		};
		
		init = function () {
			var m;
			stop();
			for (m in modules) {
				if (modules.hasOwnProperty(m)) {
					modules[m].init();
				}
			}
		};
		
		pause = function () {
			if (running && !paused) {
				paused = true;
				clumpy.pause();
			}
		};
		
		resume = function () {
			if (running && paused) {
				paused = false;
				clumpy.resume();
			}
		};
		
		stop = function () {
			if (running) {
				update();
				running = false;
				paused = false;
				clumpy.init();
				callback();
			}
		};

		next = function () {
			if (running && paused) {
				the_next();
				update();
			}
		};
		
		async = function (fn) {
			clumpy.wait(fn);
		};

	
		this.addModule = addModule;
		this.getModule = getModule;
		this.lookup = lookup;
		this.setOptions = setOptions;
		this.getOptions = getOptions;
		
		this.async = async;

		this.run = run;
		this.init = init;
		this.pause = pause;
		this.resume = resume;
		this.stop = stop;
		this.next = next;
		

		construct();

	},
	
	module: function (name, fn) {
		fn = Talky.ModuleIF(name, fn);
		return function () {
			var mem, tk, names, i;
			fn.apply(this, arguments);
			tk = this.talky;
			this.name = name;
			names = [];
			for (mem in tk) {
				if (tk.hasOwnProperty(mem)) {
					names.push(mem);
				}
			}
			for (i = names.length - 1; i >= 0; i -= 1) {
				tk[names[i]].moduleName = name;
				tk[names[i]].memberName = names[i];
			}
		};
	},
	
	ModuleIF: iFace('Talky.ModuleIF', [
		'talky',
		'init',
		'setHub',
		'changed',
		'update'
	]),
	
	InterpreterIF: iFace('Talky.InterpreterIF', [
		'parse',
		'next',
		'setHub'
	])
};

