/*!
	State Model Sample Code -- uiComponent object
	--------------------------------------------
	Copyright 2009 Kevin Dolan
	-http://www.thekevindolan.com
	
	Code licensed under the MIT license
	-See license.txt
	
	v0.1
*/

/*! public, accessible
	uiComponent constructor
	Params: record of the following
		-dataManager : dataManager object to use
		-initialize : function to call to initialize the object
		-[notReady] : function to call to indicate the component is not ready
		-[onUpdate] : function to call to update the data fields, if unset will call initialize
*/
function uiComponent(params) {
	
	this.initialize = params.initialize;
	this.dataManager = params.dataManager;
	
	if(util.isDefined(params.notReady))
		this.notReady = params.notReady;
	else
		this.notReady= function() {};
		
	if(util.isDefined(params.onUpdate))
		this.onUpdate = params.onUpdate;
	else
		this.onUpdate = params.initialize;
	
	/*! public, accessible
		draw the component with the given parameters
		Params:
			-id : id to identify this particular component
			-params : whatever parameters pertain to this component
	*/
	this.create(id, params) {
		this.currentComponent = {id: id, component: this, params: params};
		try { this.initialize(id, params) }
		catch (e) { this.notReady(id, params); }
	}
	
	/*! public, accessible
		update the component to reflect a change in data
		Params:
			-id : id to identify this particular component
			-params : whatever parameters pertain to this componen
	*/
	this.update(id, params) {
		this.currentComponent = {id: id, component: this, params: params};
		try { this.onUpdate(id, params); }
		catch (e) { this.not_ready(id, params); }
	}
	
	/*! public
		append an element to the child nodes of the target element
		if an element with that id already exists, delete it
		Params:
			-element : to be inserted
			-target : where to insert
	*/
	this.append = function(element, target) {
		id = element.getAttribute('id');
		
		try {
			old = target.getElementById(id);
			target.replaceChild(element, old);
		}
		catch(e){ target.appendChild(element); }
		
		
	}
	
	/*! public
		get a data value, throw undefined exception if the field is undefined
		Params:
			-name : name of data
			-field : specific field of the data
	*/
	this.data = function(name, field) {
		datas = this.dataManager.get(name, this.currentComponent);
		if(!util.isDefined(datas[field]))
			throw "Undefined Data Field";
		return datas[field];
			
	}
	
	
	return true;
}
