
var Gui = require ('./gui');

module.exports = new Class
({
	Extends: Vn.Component
	,Properties: {
		gui:
		{
			type: Gui
			,set: function (x)
			{
				this._gui = x;
				this.conn = x.conn;
				this.hash = x.hash;
			}
			,get: function ()
			{
				return this._gui;
			}
		},
		formInfo:
		{
			type: Object,
			value: null
		}
	}
	
	,isOpen: false
	,uiLoaded: false
	
	,loadUi: function ()
	{
		if (!this.isOpen)
			return;
	
		var builder = new Vn.Builder ();
		builder.compileFile ('forms/'+ this.formInfo.path +'/ui.xml');
		
		var extraObjects = {
			conn: this.conn,
			hash: this.hash
		};
		var scope = builder.load (this.doc, this, null, extraObjects, this.hash);
		this.scope = scope;
		this.$ = scope.$;
		this._node = this.$.main;

		var paramsLot = this.$.params;

		if (paramsLot)
		{
			paramsLot.source = this.hash;
			this.params = paramsLot;
		}
	
		scope.link ();

		var models = scope.getByTagName ('db-model');

		for (var i = 0; i < models.length; i++)
			models[i].conn = this.conn;

		var queries = scope.getByTagName ('db-query');

		for (var i = 0; i < queries.length; i++)
			queries[i].conn = this.conn;

		if (this.node)
		{
			this.gui.setForm (this.node);
			this.gui.setTitle (this.$.title);
			this.gui.setActions (this.$.actions);
			this.activate ();
		}
		
		this.uiLoaded = true;
	}
	
	,unloadUi: function ()
	{
		if (!this.uiLoaded)
			return;

		if (this.node)
		{
			this.deactivate ();
			this.scope.unref ();
			this.gui.setTitle (null);
			this.gui.setActions (null);
			this.gui.setForm (null);
			this.node = null;
			this.params = null;
		}
		if (this.scope)
		{
			this.scope.unref ();
			this.scope = null;
		}
	}

	/**
	 * Called when the form is opened.
	 */
	,open: function ()
	{
		this.close ();
		this.isOpen = true;
		this.loadUi ();
	}

	/**
	 * Called when the form is closed.
	 */
	,close: function ()
	{
		if (!this.isOpen)
			return;

		this.isOpen = false;
		this.unloadUi ();
	}
	
	/**
	 * Called when the form is activated.
	 */
	,activate: function () {}
	
	/**
	 * Called when the form is deactivated.
	 */
	,deactivate: function () {}

	,_destroy: function ()
	{
		this.close ();
		this.parent ();
	}
});

