/**
 * Copyright Intermesh
 *
 * This file is part of Group-Office. You should have received a copy of the
 * Group-Office license along with Group-Office. See the file /LICENSE.TXT
 *
 * If you have questions write an e-mail to info@intermesh.nl
 *
 * @version $Id: SieveGrid.js 0000 2010-12-29 09:03:02 wsmits $
 * @copyright Copyright Intermesh
 * @author Wesley Smits <wsmits@intermesh.nl>
 */

GO.sieve.SieveGrid = function(config){
	
	this.selectScript = new Ext.form.ComboBox({
		hiddenName:'selectScript',
		valueField:'value',
		displayField:'name',
		store: new GO.data.JsonStore({
			url:GO.settings.modules.sieve.url+'fileIO.php',
			baseParams: {
				task: 'get_sieve_scripts',
				account_id: 0
			},
			fields: ['name', 'value'],
			root: 'results'
		}),
		mode:'local',
		triggerAction:'all',
		editable:false,
		selectOnFocus:true,
		forceSelection:true,
		allowBlank:false,
		width:140
	});

	this.selectScript.on('select', function(combo, record){
		this.setSelectedScript(record.json.value);
		this.store.reload();
	},this);

	var fields ={
		fields:['id','name', 'index', 'script_name','disabled'],
		columns:[{
			header: GO.sieve.lang.name,
			dataIndex: 'name'
		},{
			header: GO.sieve.lang.disabled,
			dataIndex: 'disabled',
			renderer: function(value, metaData, record, rowIndex, colIndex, store) {
				if(value)
					value = GO.lang.cmdYes;
				else
					value = GO.lang.cmdNo;
				return value;
			}
		}
	]};

	if(!config)
	{
		config = {};
	}
	config.title=GO.email.lang.filters;
	config.layout='fit';
	config.region='center';
	config.autoScroll=true;
	config.border=false;
	config.store = new GO.data.JsonStore({
		url: GO.settings.modules.sieve.url+ 'fileIO.php',
		baseParams: {
			task: 'get_sieve_rules',
			script_name: ''
			},
		root: 'results',
		id: 'index',
		totalProperty:'total',
		fields: fields.fields,
		remoteSort: true
	});
	config.paging=true;
	var columnModel =  new Ext.grid.ColumnModel({
		defaults:{
			sortable:true,
			autoFill: true,
			forceFit: true
		},
		columns:fields.columns
	});
	config.cm=columnModel;
	config.view=new Ext.grid.GridView({
		autoFill: true,
		forceFit: true,
		emptyText: GO.lang['strNoItems']
	});
	config.sm=new Ext.grid.RowSelectionModel();
	config.loadMask=true;

	this.sieveDialog = new GO.sieve.SieveDialog();
	this.sieveDialog.on('hide', function(panel){
		this.store.reload();
	}, this);

	config.enableDragDrop=true;
	config.ddGroup='SieveFilterDD';

	config.tbar=[{
			iconCls: 'btn-add',
			text: GO.lang['cmdAdd'],
			cls: 'x-btn-text-icon',
			handler: function(){
	    	this.sieveDialog.show(-1,this.selectScript.getValue(),this.store.baseParams.account_id);
			},
			scope: this
		},{
			iconCls: 'btn-delete',
			text: GO.lang['cmdDelete'],
			cls: 'x-btn-text-icon',
			handler:function(){this.deleteSelected();},
				scope: this
		},
		GO.sieve.lang.filterset,
		this.selectScript,{
			iconCls: 'btn-delete',
			text: GO.sieve.lang.activate,
			cls: 'x-btn-text-icon',
			handler: function(){
				Ext.Ajax.request({
				 url: GO.settings.modules.sieve.url+ 'fileIO.php',
				 scope:this,
				 params: {
					 task: 'set_active_script',
					 script_name: this.selectScript.getValue(),
					 account_id: this.store.baseParams.account_id
				 },
				 success: function(){
					 this.selectScript.store.reload();
					 this.setSelectedScript();
					 this.selectScript.setRawValue(this.selectScript.getRawValue() + ' ('+GO.sieve.lang.active+')');
					 this.store.reload();
				 },
				 failure: function(){
					//TODO: nog een melding geven
				 }
				},this);
			},
			scope: this
		}];
	GO.sieve.SieveGrid.superclass.constructor.call(this, config);
	
	this.on('rowdblclick', function(grid, rowIndex){
		var record = grid.getStore().getAt(rowIndex);
		this.sieveDialog.show(record.data.index, record.data.script_name, this.store.baseParams.account_id);
		}, this);

	this.on('show', function(){
		this.store.load();
		this.selectScript.store.load({
			callback:function(){
				this.selectScript.setValue(this.selectScript.store.reader.jsonData.active);
			},
			scope:this
		});
	}, this);

	this.on('render', function(){
		//enable row sorting
		var DDtarget = new Ext.dd.DropTarget(this.getView().mainBody,
		{
			ddGroup : 'SieveFilterDD',
			copy:false,
			notifyDrop : this.onNotifyDrop.createDelegate(this)
		});
	}, this);
};

Ext.extend(GO.sieve.SieveGrid, GO.grid.GridPanel,{
	setAccountId : function(account_id){
		this.store.baseParams.account_id = account_id;
		this.selectScript.store.baseParams.account_id = account_id;
	},
	setSelectedScript : function(name){
		if(name)
			this.store.baseParams.script_name = name;
		else
			this.store.baseParams.script_name = this.selectScript.getValue();
	},
	onNotifyDrop : function(dd, e, data)
	{
		var rows=this.selModel.getSelections();
		var dragData = dd.getDragData(e);
		var cindex=dragData.rowIndex;
		if(cindex=='undefined')
		{
			cindex=this.store.data.length-1;
		}

		for(i = 0; i < rows.length; i++)
		{
			var rowData=this.store.getById(rows[i].id);

			if(!this.copy){
				this.store.remove(this.store.getById(rows[i].id));
			}

			this.store.insert(cindex,rowData);
		}

		//save sort order
		var filters = [];

		for (var i = 0; i < this.store.data.items.length;  i++)
		{
			filters.push(this.store.data.items[i].get('index'));
		}

		Ext.Ajax.request({
			url: GO.settings.modules.sieve.url+'fileIO.php',
			params: {
				task: 'save_scripts_sort_order',
				sort_order: Ext.encode(filters),
				account_id: this.store.baseParams.account_id
			}
		});
	}
});