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 conn = this.conn;
		var hash = this.hash;

		var extraObjects = {
			conn: conn,
			hash: hash
		};
		var scope = builder.load (this.doc, this, null, extraObjects, hash);
		this.scope = scope;
		this.$ = scope.$;
		this._node = this.$.main;

		var paramsLot = this.$.params;

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

		function setConnection (tagName)
		{
			var objects = scope.getByTagName (tagName);
			for (var i = 0; i < objects.length; i++)
				objects[i].conn = conn;
		}

		var tags = ['db-model', 'db-query', 'db-lot'];
		for (var i = 0; i < tags.length; i++)
			setConnection (tags[i]);

		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 ();
	}
});