
var VnObject = require ('./object');

var scopeUid = 0;

module.exports = new Class
({
	Extends: VnObject

	,initialize: function (builder, objects, thisArg, parentScope, lot)
	{
		this.builder = builder;
		this.objects = objects;
		this.thisArg = thisArg;
		this.parentScope = parentScope;
		this.uid = ++scopeUid;
		this.lot = lot;

		if (!thisArg && parentScope)
			this.thisArg = parentScope.thisArg;

		this.parent ();
	}

	,init: function (extraObjects)
	{
		var contextMap = this.builder._contextMap;
		var objectMap = this.parentScope ? Object.create (this.parentScope.$) : {};
		this.$ = objectMap;

		for (var id in extraObjects)
			objectMap[id] = extraObjects[id];
		for (var id in contextMap)
			objectMap[id] = this.objects[contextMap[id]];
	}

	,getMain: function ()
	{
		return this.builder.getMain (this);
	}
	
	/**
	 * Fetchs a set of elements by it's tag name.
	 *
	 * @param {String} tagName The object tag name
	 * @return {Array[Object]} The list of objects or an empty array
	 */
	,getByTagName: function (tagName)
	{
		return this.builder.getByTagName (this, tagName);
	}

	/**
	 * Links all scope objects and connects it's events.
	 */
	,link: function ()
	{
		this.builder.link (this);
	}

	,getMethod: function (value, binded)
	{	
		if (this.thisArg)
			var method = this.thisArg[value];
		else
			var method = window[value];
			
		if (method && binded)
			method = method.bind (this.thisArg);

		if (method === undefined)
			this.builder.showError ('Function \'%s\' not found', value);

		return method;
	}

	,getHtmlId: function (nodeId)
	{
		return 'vn-'+ this.uid +'-'+ nodeId;
	}
	
	,_destroy: function ()
	{
		this.builder.freeScope (this);
		this.parent ();
	}
});
