"use strict";
/*
eventScript is a sparse array where
eventScript[framesSinceStart] = {
	controls : {
		"gameObjectName" : {
			input : boolean,
			input : boolean
			...
		}
	},
	customPre : function(cacheVars){...}, // executed before setting controls
	customPost : function(cacheVars){...} // executed after setting controls
}

objMgr is a GameObjectManager ideally containing all named GameObjects used by the event
dlgMgr is a DialogueManager used to launch dialogues from within an event
*/
var ScriptedEvent = function(eventScript, cacheVars, objMgr, dlgMgr){
	this.objMgr = objMgr;
	this.script = [];
	// store in sparse object form; use in Array form for .length
	for (var evt in eventScript){
		this.script[evt] = eventScript[evt];
	}
	//this.frameCounter=0;
	this.objects = {};
	this.cacheVars = {};
	this.cacheVars.wait = false; // special cache var for halting the frame counter e.g. until a dialogue ends
	this.cacheVars.objMgr = objMgr;
	this.cacheVars.dlgMgr = dlgMgr; // a special cache var for letting events launch dialogues
	this.cacheVars.frameCounter=0; // event timing; exposed to the scripter to allow custom control
	this.cacheVars.uncacheObjects = []; // normally, any object listed in controls is looked up once and cached.  Push names into this array to have them cleared from cache and looked up fresh when needed.
	this.frameCounter = 0; // remember where we were at the start of an evaluation so we know if it's changed
	for (var cacheVar in cacheVars){
		this.cacheVars[cacheVar] = cacheVars[cacheVar];
	}
}
	ScriptedEvent.prototype.Update = function(){
		if (!this.cacheVars.wait){
			this.frameCounter = this.cacheVars.frameCounter;
			if (this.script[this.cacheVars.frameCounter]){
				if (this.script[this.cacheVars.frameCounter].customPre){
					this.script[this.cacheVars.frameCounter].customPre(this.cacheVars);
				}

				if (this.cacheVars.frameCounter==this.frameCounter){ // only continue execution of this step if the pre didn't skip ahead
					if (this.cacheVars.uncacheObjects.length){
						for (var i=0; i<this.cacheVars.uncacheObjects.length; ++i){
							this.objects[this.cacheVars.uncacheObjects[i]]=null;
						}
						this.cacheVars.uncacheObjects.length=0;
					}
					for (var name in this.script[this.cacheVars.frameCounter].controls){
						if (!this.objects[name]){
							this.objects[name] = this.objMgr.getNamedObject(name);
						}
						if (this.objects[name] && (this.objects[name].interactions & DEFINE_GAMEOBJECT_INTERACTIONS.CONTROL)){
							this.objects[name].controls.setInputs(this.script[this.cacheVars.frameCounter].controls[name]);
						}
					}

					if (this.script[this.cacheVars.frameCounter].customPost){
						this.script[this.cacheVars.frameCounter].customPost(this.cacheVars);
					}
				}
			}
			this.cacheVars.frameCounter++; // yes, this means that any pre/post scripted jumps should be 1 shy of target
			return (this.cacheVars.frameCounter>=this.script.length);
		}
		return false;
	};
	