
Hedera.Queries = new Class
({
	Extends: Hedera.Form
	
	,activate: function  ()
	{
		this.$.resultIndex.value = 0;
	}
	
	,clean: function ()
	{
		if (this._grid)
		{
			this.$.gridHolder.removeChild (this._grid.node);
			this._grid.unref ();
			this._grid = null;
		}
	}
	
	,_onExecuteClick: function ()
	{
		this.clean ();
		
		var model = new Db.Model ({
			conn: this.conn,
			query: this.$.sql.value,
			resultIndex: this.$.resultIndex.value,
			updatable: this.$.updatable.value
		});
		model.on ('status-changed', this._onModelChange, this);
	}
	
	,_onCleanClick: function ()
	{
		this.clean ();
	}
	
	,_onModelChange: function (model, status)
	{
		if (status !== Db.Model.Status.LOADING)
		{
			model.disconnect ('status-changed', this._onModelChange, this);
			model.unref ();
		}

		if (status !== Db.Model.Status.READY)
			return;

		Htk.Toast.showMessage (_('Query executed!'));

		var gridHolder = this.$.gridHolder;
		
		if (gridHolder.firstChild)
			gridHolder.removeChilds (gridHolder.firstChild);

		var grid = new Htk.Grid ();
		
		var columns = model.columns;
		
		for (var i = 0; i < columns.length; i++)
		{
			var c = columns[i];
		
			switch (c.type)
			{
				case Db.Conn.Type.BOOLEAN:
					var column = new Htk.ColumnCheck ();
					break;
				case Db.Conn.Type.INTEGER:
					var column = new Htk.ColumnSpin ();
					break;
				case Db.Conn.Type.DOUBLE:
					var column = new Htk.ColumnSpin ({digits: 2});
					break;
				case Db.Conn.Type.DATE:
					var column = new Htk.ColumnDate ({format: '%a, %e %b %Y'});
					break;
				case Db.Conn.Type.DATE_TIME:
					var column = new Htk.ColumnDate ({format: '%a, %e %b %Y, %T'});
					break;
				case Db.Conn.Type.STRING:
				default:
					var column = new Htk.ColumnText ();
			}
		
			column.setProperties ({
				title: c.name,
				editable: this.$.updatable.value,
				columnIndex: i
			});
			
			grid.appendColumn (column);
		}
		
		grid.model = model;
		gridHolder.appendChild (grid.node);
		this._grid = grid;
	
	}
});

