<?php 

include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_grid.php");

$templateId = $_POST['node_id'];
$templateName = $_POST['name'];

$grid = new MakeGrid('wupQueryMachineGrid_'.$templateId);
$grid->setMainTable('_QueryMachineConstruction',DB_WARPIT_USERSPOOL)
	->setTitle($templateName)
	->baseParams = "SQLwhere : 'id_template = $templateId'"
;
// create the combo instance
echo "//combo box for condition choise
var andOrCombo = new Ext.form.ComboBox({
    typeAhead: true,
    triggerAction: 'all',
    lazyRender:true,
    mode: 'local',
    store: new Ext.data.ArrayStore({
        id: 0,
        fields: [
            'myId',
            'displayText'
        ],
        data: [['AND', 'AND'], ['OR', 'OR']]
    }),
    valueField: 'myId',
    displayField: 'displayText'
	});
	//open bracket combobox
var openBracketCombo = new Ext.form.ComboBox({
    typeAhead: true,
    triggerAction: 'all',
    lazyRender:true,
    mode: 'local',
    store: new Ext.data.ArrayStore({
        id: 0,
        fields: [
            'myId',
            'displayText'
        ],
        data: [['', '/'], ['(', '(']]
    }),
    valueField: 'myId',
    displayField: 'displayText'
	});
	//close bracket combo
	var closeBracketCombo = new Ext.form.ComboBox({
    typeAhead: true,
    triggerAction: 'all',
    lazyRender:true,
    mode: 'local',
    store: new Ext.data.ArrayStore({
        id: 0,
        fields: [
            'myId',
            'displayText'
        ],
        data: [['', '/'], [')', ')']]
    }),
    valueField: 'myId',
    displayField: 'displayText'
	});
	//combobox for operation choises
	var wupOperationCombo = new Ext.form.ComboBox({
    typeAhead: true,
    triggerAction: 'all',
    lazyRender:true,
    mode: 'local',
    store: new Ext.data.ArrayStore({
        id: 0,
        fields: [
            'myId',
            'displayText'
        ],
        data: [['=', '='], ['!=', '!='], ['<', '<'], ['>', '>'], ['LIKE', 'LIKE']]
    }),
    valueField: 'myId',
    displayField: 'displayText'
	});
	//combobox (tree) for all possible fields
	var wupQueryFieldCombo = new Ext.ux.TreeCombo({maxHeight:500,loader : new Ext.tree.TreeLoader({
 dataUrl   	:'webuserspool/_ajax/ajax.queryMachine.php', preloadChildren:true,
 baseParams	: {RMtable:'_QueryMachineFields',database:'".DB_WARPIT_USERSPOOL."',action:'selectAll',RMcomp:'tree', boldRoots : true} 
,listeners: { load : function(a,b,resp){ var r = Ext.decode(resp.responseText); if(r!= null && r.success === false){ alert('Tree load error: '+r.error,'Error'); }  }
				} }
				) //eo treeLoader
,
onTreeNodeClick: function(node, e) {
		if(!node.attributes.leaf) return;
        this.setRawValue(node.text);
        this.value = node.id;
        this.fireEvent('select', this, node);
        this.collapse();
    }
				});
	
	wupQueryFieldCombo.treePanel.expandAll();	
var treeComboToRenderer = function(combo) 
	{ return function(value) { 
		var idx = combo.treePanel.getRootNode().findChild('id' , value,true);
		if(idx==null)	return 'Select';
		return idx.attributes.text;
		}
	}
	
	
";
$gridName = $grid->getName();
$grid->addConfig('editors','[ [],[],new Ext.form.TextField(),new Ext.form.DateField() ]')
	->setReqUrl('webuserspool/_ajax/ajax.queryMachine.php')
;
$grid->addColumn('id');
$grid->addColumn('id_template')->defaultValue($templateId);
$grid->setSort('orderBy');
//a bit of a hack...we add the order of the where clause
$grid->addColumn('orderBy')->defaultValue("\"+$gridName.getStore().getCount() +\"");
	
$grid->addColumn('conditionField','Condition' )->editor('andOrCombo')->defaultValue('AND')
	->renderer("function(val,mt,rec,ind){ return ind == 0 ? '' : val;  }")
;
$grid->addColumn('openBracket','(')->editor('openBracketCombo');
$grid->addColumn('field_id','Field')->editor("wupQueryFieldCombo")->renderer("treeComboToRenderer(wupQueryFieldCombo)")
	->defaultValue('Groups')
;
//a variable that stores the value fetched from the database, so that we can show it if the tree isn't loaded!
$grid->addColumn('groupName');
$grid->addColumn('comboName');
$grid->addColumn('operation','Operation' )->editor('wupOperationCombo')->defaultValue('=');
$grid->addColumn('valueField','Value')->editor('new Ext.form.TextField()')
	->setProperty('getEditor',"function(rI){
	var rec = $gridName.getStore().getAt(rI);
	var node = wupQueryFieldCombo.treePanel.getRootNode().findChild('id',rec.data.field_id,true);
			if(node == null)
				return;
			var nodeRec = node.attributes;
	if(nodeRec.isField )
	{
		if(nodeRec.displayType == 2 || nodeRec.displayType == 3 || nodeRec.displayType == 4 )
		{
			return $gridName.editors[0][ rec.id ];
		}
		else if(nodeRec.displayType == 5)
		{
			return $gridName.editors[3];
		}
		else 
		{
			return $gridName.editors[2];
		}
	}
		return $gridName.editors[1][ rec.id ];
}")
	->renderer("function(value, metadata, gridRec, rowIndex, colIndex, store){
        var editor = $gridName.getColumnModel().getCellEditor(colIndex, rowIndex),
            field = editor ? editor.field : null;
            
        if(field){
        	if(field.findRecord)
        	{ 
	            var record = field.findRecord(field.valueField, value);
	            var rec = $gridName.getStore().getAt(rowIndex);
	            field.burek = rec.data.field_id;
	            return record ? record.get(field.displayField) : (gridRec.data.comboName ? gridRec.data.comboName : 'Select');
	         }
	         else if(field.treePanel) 
	         { 
	         	var idx = field.treePanel.getRootNode().findChild('id' , value,true);
				if(idx==null)	return gridRec.data.groupName ? gridRec.data.groupName : 'Select';
				return idx.attributes.text;
	         }
	         else if(field.getXType() == 'datefield')
	         {
	         	
	         	return Ext.util.Format.date(Date.parseDate(value,'Y-m-d'),'d.m.Y');
	         }
        }
        return value;
    }")
;
$grid->addColumn('closeBracket',')')->editor('closeBracketCombo');
$grid->addConfig('clicksToEdit','1');
$grid->addConfig('configEditors',"function(rec){
			//for each record we must configure it's own uniqe editor
			var node = wupQueryFieldCombo.treePanel.getRootNode().findChild('id',rec.data.field_id,true);
			if(node == null)
				return;
			var nodeRec = node.attributes;
	
			if(nodeRec.isField )
			{
				if(nodeRec.displayType == 2 || nodeRec.displayType == 3 || nodeRec.displayType == 4 )
				{
					$gridName.editors[0][ rec.id  ] = new Ext.form.ComboBox({
								store: new Ext.data.JsonStore({autoLoad:true,
								url:'_ajaxManipulators/gridDataManipulator.php',
								baseParams:{action:'select',database:'".DB_WARPIT_USERSPOOL."',RMtable:'user_input_labels'
								, SQLwhere :'lab_field = ' + nodeRec.idOrg },root:'rows',
								fields:['lab_code','lab_label'],
								listeners:{load: function(str,recs){
									//$gridName.getView().refresh();
								} }}),
								displayField:'lab_label',valueField:'lab_code',
								triggerAction:'all',mode:'local'
								});
				//	$gridName.editors[0][ rec.id  ].getStore().load( {params:{ SQLwhere :'lab_field = ' + nodeRec.idOrg    }  }  );
				}
				
			}
			else 
			{
				var ld = {};
				ld.action = 'select';
				var dataUrl = '_ajaxManipulators/treeDataManipulator.php';
				if(rec.data.field_id == 'Projects' )
				{
					ld.RMcomp = 'tree';
					ld.RMtable='_Projects';
					dataUrl = 'webcati/_forms/_ajax/ajax.groups.php';
					ld.database='".DB_WARPIT_WEBCATI_BASE."';	
					ld.RMorder = 'idLab ASC';
				}
				else if(rec.data.field_id == 'Groups' )
				{
					ld.RMtable='_groups';
					ld.database='".DB_WARPIT_USERSPOOL."';	
				}
				else if(rec.data.field_id == 'Gained' || rec.data.field_id == 'Used' || rec.data.field_id == 'Total')
				{
					$gridName.editors[1][ rec.id  ] = new Ext.form.NumberField();
					return;
				}
				else 
				{
					$gridName.editors[1][ rec.id  ] = new Ext.form.TextField();
					return;
				}
				
				$gridName.editors[1][ rec.id  ] = new Ext.ux.TreeCombo({autoHeight:true,loader : new Ext.tree.TreeLoader({
				 dataUrl   	:dataUrl, 
				 baseParams	: ld 
				,listeners: { load : function(a,b,resp){ var r = Ext.decode(resp.responseText); 
					if(r!= null && r.success === false){ alert('Tree load error: '+r.error,'Error'); }
					else{if(!a.RMload) //$gridName.getView().refresh(); 
					a.RMload = true;  }
					  }
						} }
						) //eo treeLoader
						,
				onTreeNodeClick: function(node, e) {
						if(!node.attributes.leaf) return;
				        this.setRawValue(node.text);
				        if(node.attributes.id_project)
				        	this.value = node.attributes.id_project;
				        else
				        	this.value = node.id;
				        this.fireEvent('select', this, node);
				        this.collapse();
				    }
						});
				
			}
}")
->activateAdd('Add','icon-add-record',"$gridName.configEditors( $gridName.getStore().getAt(lastRow)  ) ")
->activateRemove()
->setSortable(false)
->addTbarItem("{text:'Create Query',handler:function(){
		
	 addTabAuto('wupShowGroupQuery_$templateId','webuserspool/_forms/forms.showgroup.php',{template_id: $templateId,name:'$templateName' }); 
}}")
;

echo $grid->createGrid();

echo "
	$gridName.on('afteredit',function(e){
		if(e.field == 'field_id')
		{
			e.record.set('valueField','');
			e.record.set('groupName','');
			e.record.set('comboName','');
			$gridName.configEditors(e.record);
		}
		
		
	});
	$gridName.getStore().on('load',function(store,recs){
		Ext.each(recs,function(rec){
			$gridName.configEditors(rec);
		});
		$gridName.getView().refresh();
	});
Ext.getCmp( 'queryMachineTabPanel').add( $gridName ).show();  "

?>