
/*
 
   SqlPanel object provides handlers for the SQL Command page.
   call init_handlers from main.html, after creating the object.
 
*/ 

function SqlPanel(rdbAdmin)
{
	if (!rdbAdmin) {
		alert('bad rdbAdmin');
	}
	this.rdbAdmin = rdbAdmin;
	this.sqlEngine = rdbAdmin.sqlEngine;
	this.sqlResults = null;
	this.formId = 'sql-panel-form';
	this.cMediter = undefined;
	
	this.init_handlers = function(query)
	{
			var $this = this;
			$('#sqlcommand').click(function(){$this.showQuery();});
			var $form = $('#'+this.formId);
			$form.find('#query-execute-button').click(function() {
					$this.rdbAdmin.resetMessages(); 
					$this.executeQuery();
			});
			$form.find('table button').click(function () {
					$(this).parent().children(':input').toggle();
			});
			this.initCodeMirror($form,
								'\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n');
	};

	this.initCodeMirror = function($form,query)
	{
		// too busy/lazy to find out why ie handles this badly, so just dodge
		//   with browser detection.
		function qta_add(cme) {
			var $qta = $form.find('#query-text-area');
			$qta.after($(cme));
		}
		if ( !$.browser.msie ) {
			if ( !this.cMediter ) {
				//var qta = CodeMirror.replace('query-text-area');
				this.cMediter = new CodeMirror(qta_add,
						{   parserfile: 'parseplsql.js',
							path: 'codemirror/js/',
							stylesheet: 'codemirror/css/plsqlcolors.css',
							height: '450px',
							textWrapping: false,
							content: query  }
				);
			}
			else {
				this.cMediter.setCode(query);
			}
			$('#query-text-area').hide();
		}
		else {
			$('#query-text-area').val(query);
			$('#codemirror-credit').hide();
		}
	};
		
	this.showQuery = function(query)
	{
		this.rdbAdmin.resetMessages();
		var $this = this;
		var $form = $('#'+this.formId);
		if (!this.rdbAdmin.isLoggedIn()) {
			alert('You must login first!');
			return false;
		}
		this.clearPanel();
		this.rdbAdmin.setHeading("Perform SQL Query");
		this.rdbAdmin.showPanel("sql-panel");
		$form.find('table :input').each(function () {
			var typ = $(this).attr('type'),
			    lbl;
			if (typ === 'file') {
				$(this).hide();
			}
			else if (typ === 'text') {
				$(this).show();
			}
			else if (typ === 'button') {
				$this = $(this);
				lbl = $this.html();
				$this.removeAttr('name');
				if (lbl === 'file') {
					$this.show();
				}
				else {
					$this.hide();
				}
			}
		});
		this.initCodeMirror($form,query);
		return true;
	};

	this.clearPanel = function()
	{
		$("[id=query-display]").empty().hide();
		$("[id=query-results-table]").empty().hide();
		$("[id=query-text-area]").empty();
		this.rdbAdmin.showPanel("sql-panel");
	};

	this.executeQuery = function()
	{
		var $this = this;
		var $panel = $('#sql-panel');
		$panel.find('#query-results-table').empty();		
		var $qta = $panel.find('#query-text-area');
		var query;
		if ( this.cMediter ) {
			query = this.cMediter.getCode();
			$qta.val(query);
		}
		else {
			query = $qta.val();
		}
		//query = query.replace(/%/g,'%%');
		// prep arg### fields
		$panel.find(':input[id^=arg0]:visible').each(function () {
			var $argid = $(this).attr('id');
			$(this).attr('name',$argid.substr(0,6));
		});
		// functions to handle results of query submit
		function errback (err,msg) {
			$this.rdbAdmin.showErrorMessage('<pre>'+err.toString()+': '+msg+'</pre>');
		}
		function callback (data) {
			if (data.status[0] !== 'error')  {
				$this.rdbAdmin.updateTableList();
				$this.rdbAdmin.updateViewList();
				$this.rdbAdmin.updateSchemaList();
				$this.sqlResults = data;
				if (data.row_count[0] === 0) {
					$this.rdbAdmin.showWorkingMessage('Result is empty, 0 rows.');
				}
				else {
					$this.rdbAdmin.showWorkingMessage(data.status[1]);
					$this.fillResultsTable();
					$panel.find("#query-results-table").show();
					$panel.find("#query-display").show().append(query);
				}
			} 
			else {
				alert('error wrongly passed to success callback '+str(data.error[1]) );
			}
		}
		// querying
		this.sqlEngine.queryByForm( { 'formId' : this.formId,
								      'callback' : callback,
									  'errback' : errback  });
		return false;
	};

	this.fillResultsTable = function()
	{
		var cell;
		var tab = document.getElementById("query-results-table");
		var tabHeader = document.createElement("thead");
		var tabBody = document.createElement("tbody");
		if (this.sqlResults.records.header) {
			for (var i in this.sqlResults.records.header)  {
				if (this.sqlResults.records.header.hasOwnProperty(i)) {	
					var col = this.sqlResults.records.header[i][1];	
					cell = document.createElement("th");	
					cell.appendChild(document.createTextNode(col));
					tabHeader.appendChild(cell);
				}
			}
			var tabRow, row;
			for (i in this.sqlResults.records.rows) {
				if (this.sqlResults.records.rows.hasOwnProperty(i)) {
					row = this.sqlResults.records.rows[i];
					tabRow = document.createElement("tr");
					for (var j in row) {
						if (row.hasOwnProperty(j)) {
							cell = document.createElement("td");
							cell.appendChild(document.createTextNode(row[j]));
							tabRow.appendChild(cell);
						}
					}
				}
				tabBody.appendChild(tabRow);
			}
			tab.appendChild(tabHeader);
			tab.appendChild(tabBody);
		}
	};

}