/**
 * Project      : AMDA-NG4
 * Name         : TableDefPlugUI.js
 * @class   amdaUI.TableDefPlugUI 
 * @extends Ext.util.Observable
 * @brief   Table definition Plugin used in MyDataUI
 * @author  benjamin
 * @version 
 *
 ******************************************************************************
 *    FT Id     :   Date   : Name - Description
 ******************************************************************************
 *
 *	:           :10/06/2015: BRE - Creation
 */


/**
 * @plugin tabledef
 * @extends Ext.util.Observable 
 * @ptype tabledef
 */

Ext.define('amdaUI.TableDefPlugUI', {
	extend: 'Ext.util.Observable',
	
	alias: 'plugin.tabledef',
	
	win: null,
	
	tableDefTypeCombo: null,
	channelsDefTypeCombo: null,
	nameField: null,
	unitsField: null,
	defMainPanel: null,
	
	manualDefGrid: null,
	
	constructor: function(config) { 
		Ext.apply(this, config);  
		this.callParent(arguments);
	},

	init: function(cmp) 
	{  
	    this.hostCmp = cmp;
	    this.hostCmp.on({
	        scope: this,		 	       
	        added: function(){
		    this.hostCmp.ownerCt.on({
		      render: this.onRender,
	          hide : this.onHide,
		      scope: this });		   
	        }
	    }); 
	   
	    var tableDefTypeStore = Ext.create('Ext.data.Store', {
            fields: ['value', 'name'],
            data : [
                {"value": "NONE", "name":"None"},
                {"value": "MANUAL", "name":"Manual"},
                {"value": "SELECT", "name":"Select in file"}
            ]
        }); 
		
		this.tableDefTypeCombo = Ext.create('Ext.form.ComboBox', {
			fieldLabel: 'Table definition type',
	        store: tableDefTypeStore,
	        queryMode: 'local',
	        displayField: 'name',
	        valueField: 'value',
	        editable: false,
            value: 'NONE',
            listeners: {
            	scope: this,
            	'change' : function (combo, newValue, oldValue, eOpts) {
            		this.selectTableDefType(newValue);
            	}
            }
		});
		
		var channelsDefTypeStore = Ext.create('Ext.data.Store', {
            fields: ['value', 'name'],
            data : [
                {"value": "MINMAX", "name":"Min & Max"},
                {"value": "BOUND", "name":"Bound"},
                {"value": "CENTER", "name":"Center & Constant width"},
                {"value": "CENTERWIDTH", "name":"Center & Width"}
            ]
        });
		
		this.channelsDefTypeCombo = Ext.create('Ext.form.ComboBox', {
			fieldLabel: 'Channels definition type',
	        store: channelsDefTypeStore,
	        queryMode: 'local',
	        displayField: 'name',
	        valueField: 'value',
	        editable: false,
            value: 'MINMAX',
            listeners: {
            	scope: this,
            	'change' : function (combo, newValue, oldValue, eOpts) {
            		this.reconfigureDefPanel(this.tableDefTypeCombo.getValue(), newValue);
            	}
            }
		});

		this.nameField = Ext.create('Ext.form.field.Text',{
			fieldLabel: 'Table name',
			name: 'name'
		});

		this.unitsField = Ext.create('Ext.form.field.Text',{
			fieldLabel: 'Table units',
			name: 'units'
		});
		
		this.defMainPanel = Ext.create('Ext.form.Panel', {
			border: false, frame: true, plain: true,
			flex: 1,
			layout: {
		        type: 'vbox',
		        align : 'stretch'
		    }
		});
	},
	
	onRender: function() 
	{
		this.win = new Ext.Window({
			width: 400, 
			height: 400,
			x: 380, y: 0,
			baseCls:'x-panel',	 
			title: 'Table definition',
			layout: 'fit',
			closable: false,
			collapsible: true,
			constrain: true,
			floating: true,
			ghost: false,
			renderTo: this.hostCmp.id,
			items: this.getFormConfig(),
			listeners : {
				boxready: function (w) 
				{
					if (w.y + w.height > myDesktopApp.desktop.el.getHeight())
						w.el.setY((myDesktopApp.desktop.el.getHeight()-w.height > 0) ? myDesktopApp.desktop.el.getHeight()-w.height : 0);
        		}
			},
			getConstrainVector: function(constrainTo){
				var me = this;
		        if (me.constrain || me.constrainHeader) {
		            constrainTo = constrainTo || (me.floatParent && me.floatParent.getTargetEl()) || me.container || me.el.getScopeParent();
		            return (me.constrainHeader ? me.header.el : me.el).getConstrainVector(constrainTo);
		        }
		    }
		});	
	},
	
	show: function() {
		this.win.show(); 
	},
	
	hide: function() {
		this.win.hide(); 
	},
	
	showHide: function() {
		if (this.win.isVisible())
			this.hide();
		else
			this.show();
	},
	
	onHide : function()
	{
		this.hide(); 
	},
 	
	getFormConfig: function(){
		return {
			xtype: 'panel',
			border: false, frame: true, plain: true,
			layout: {
		        type: 'vbox',
		        align : 'stretch'
		    },
		    items: [
		            this.tableDefTypeCombo,
		            this.channelsDefTypeCombo,
			    this.nameField,
			    this.unitsField,
		            this.defMainPanel
		    ]
		};					 
	},
	
	selectTableDefType : function (type)
	{
		switch (type)
		{
		case 'MANUAL' :
			this.channelsDefTypeCombo.setDisabled(false);
			break;
		case 'SELECT' :
			this.channelsDefTypeCombo.setDisabled(false);
			break;
		default:
			this.channelsDefTypeCombo.setDisabled(true);
		}
		
		this.reconfigureDefPanel(type,this.channelsDefTypeCombo.getValue());
	},
	
	reconfigureDefPanel : function (tableDefType, channelsDefType)
	{
		if (this.defMainPanel == null)
			return;
		
		this.defMainPanel.removeAll(false);
		
		if (channelsDefType == 'CENTER')
		{
			this.defMainPanel.add(Ext.create('Ext.form.field.Number',{
				fieldLabel: 'Constant width',
		        name: 'width',
		        value: 1,
		        minValue: 0,
		        allowDecimals : true,
		        hideTrigger: true
			}));
		}
		
		switch (tableDefType)
		{
		case 'MANUAL' :
			this.defMainPanel.add(this.getManualDefGrid());
			this.reconfigureManualDefGrid(channelsDefType);
			break;
		case 'SELECT' :
			switch (channelsDefType)
			{
			case 'MINMAX' :
				this.defMainPanel.add(Ext.create('Ext.form.field.Text',{
					fieldLabel: 'Min',
			        name: 'min'
				}));
				this.defMainPanel.add(Ext.create('Ext.form.field.Text',{
					fieldLabel: 'Max',
			        name: 'max'
				}));
				break;
			case 'BOUND' :
				this.defMainPanel.add(Ext.create('Ext.form.field.Text',{
					fieldLabel: 'Bound',
			        name: 'bound'
				}));
				break;
			case 'CENTER' :
				this.defMainPanel.add(Ext.create('Ext.form.field.Text',{
					fieldLabel: 'Center',
			        name: 'center'
				}));
				break;
			case 'CENTERWIDTH' :
				this.defMainPanel.add(Ext.create('Ext.form.field.Text',{
					fieldLabel: 'Center',
			        name: 'center'
				}));
				this.defMainPanel.add(Ext.create('Ext.form.field.Text',{
					fieldLabel: 'Width',
			        name: 'width'
				}));
				break;
			default:
				//Nothing to do
			}
			break;
		default:
			//Nothing to do
		}
		this.defMainPanel.doLayout();
	},
	
	getManualDefGrid : function ()
	{
		if (this.manualDefGrid != null)
			return this.manualDefGrid;
		
		var store = Ext.create('Ext.data.Store', {
		    fields: ['index']
		});
		
		this.manualDefGrid = Ext.create('Ext.grid.Panel', {
			title: 'Manual channels definition',
			autoScroll: true,
			sortableColumns: false,
			store: store,
			flex: 1,
		    columns: [{ text: 'Index',  dataIndex: 'index' }],
		    plugins: [
		              Ext.create('Ext.grid.plugin.CellEditing', {
		            	  clicksToEdit: 1
		              })
		    ]
		});
		
		return this.manualDefGrid;
	},
	
	reconfigureManualDefGrid: function(type)
	{
		if (this.manualDefGrid == null)
			return;
		
		var fields = ['index'];
		var columns = [{text: 'Index',  dataIndex: 'index'}];
		
		switch (type)
		{
		case 'MINMAX' :
			fields.push({'name' : 'min', type: 'number'});
			fields.push({'name' : 'max', type: 'number'});
			columns.push({text: 'Min.',  dataIndex: 'min', editor: { xtype: 'numberfield', allowDecimals : true, hideTrigger: true}});
			columns.push({text: 'Max.',  dataIndex: 'max', editor: { xtype: 'numberfield', allowDecimals : true, hideTrigger: true}});
			break;
		case 'BOUND' :
			fields.push({'name' : 'bound', type: 'number'});
			columns.push({text: 'Bound',  dataIndex: 'bound', editor: { xtype: 'numberfield', allowDecimals : true, hideTrigger: true}});
			break;
		case 'CENTER' :
			fields.push({'name' : 'center', type: 'number'});
			columns.push({text: 'Center',  dataIndex: 'center', editor: { xtype: 'numberfield', allowDecimals : true, hideTrigger: true}});
			break;
		case 'CENTERWIDTH' :
			fields.push({'name' : 'center', type: 'number'});
			fields.push({'name' : 'width', type: 'number'});
			columns.push({text: 'Center',  dataIndex: 'center', editor: { xtype: 'numberfield', allowDecimals : true, hideTrigger: true}});
			columns.push({text: 'Width',  dataIndex: 'width', editor: { xtype: 'numberfield', allowDecimals : true, hideTrigger: true}});
			break;
		}
		
		var store = Ext.create('Ext.data.Store', {
		    fields: fields
		});
		
		this.manualDefGrid.reconfigure(store, columns);
		
		this.loadManualGridData(type, null);
	},
	
	loadManualGridData: function(type, data)
	{
		if (this.manualDefGrid == null)
			return;
		
		this.manualDefGrid.getStore().removeAll();
		
		if (!this.hostCmp.getParameterSize())
			return;	
		
		var paramSize = this.hostCmp.getParameterSize();
		
		switch (type)
		{
		case 'MINMAX' :
			var minData, maxData = null;
			if (data && data['min'])
				minData = data['min'].split(',');
			if (data && data['max'])
				maxData = data['max'].split(',');
			for (i = 0; i < paramSize; ++i)
			{
				if (minData && maxData && (i < minData.length) && (i < maxData.length))
					this.manualDefGrid.getStore().add({'index' : i, 'min' : parseFloat(minData[i]), 'max' : parseFloat(maxData[i])});
				else
					this.manualDefGrid.getStore().add({'index' : i, 'min' : i, 'max' : i+1});
			}
			break;
		case 'BOUND' :
			var boundData = null;
			if (data && data['bound'])
				boundData = data['bound'].split(',');
			for (i = 0; i < paramSize + 1; ++i)
			{
				if (boundData && (i < boundData.length))
					this.manualDefGrid.getStore().add({'index' : i, 'bound' : parseFloat(boundData[i])});
				else
					this.manualDefGrid.getStore().add({'index' : i, 'bound' : i});
			}
			break;
		case 'CENTER' :
			var centerData = null;
			if (data && data['center'])
				centerData = data['center'].split(',');
			for (i = 0; i < paramSize; ++i)
			{
				if (centerData && (i < centerData.length))
					this.manualDefGrid.getStore().add({'index' : i, 'center' : parseFloat(centerData[i])});
				else
					this.manualDefGrid.getStore().add({'index' : i, 'center' : i+0.5});
			}
			break;
		case 'CENTERWIDTH' :
			var centerData, widthData = null;
			if (data && data['center'])
				centerData = data['center'].split(',');
			if (data && data['width'])
				widthData = data['width'].split(',');
			for (i = 0; i < paramSize; ++i)
			{
				if (centerData && widthData && (i < centerData.length) && (i < widthData.length))
					this.manualDefGrid.getStore().add({'index' : i, 'center' : parseFloat(centerData[i]), 'width' : parseFloat(widthData[i])});
				else
					this.manualDefGrid.getStore().add({'index' : i, 'center' : i+0.5, 'width' : 1});
			}
			break;
		}
			
		this.manualDefGrid.getView().refresh();
	},
	
	loadSelectData : function(data)
	{
		this.defMainPanel.getForm().getFields().each(function (item, index, len) {
			if (data[item.name])
				item.setValue(data[item.name]);
		});
	},
	
	getTableDefinitionObject : function()
	{
		var obj = {
				'tableDefType' : this.tableDefTypeCombo.getValue(),
				'channelsDefType' : this.channelsDefTypeCombo.getValue(),
				'tableName' : this.nameField.getValue(),
				'tableUnits' : this.unitsField.getValue(),
				'data' : {}
		};
		
		if (obj.tableDefType == 'NONE')
			return obj;
		
		this.defMainPanel.getForm().getFields().each(function (item, index, len) {
			obj.data[item.name] = item.getValue();
		});
		
		if (obj.tableDefType == 'MANUAL')
		{
			if (this.manualDefGrid.getStore().getCount() > 0)
			{
				var firstData = this.manualDefGrid.getStore().getAt(0);
				for (i = 0; i < firstData.fields.items.length; ++i)
				{
					if ((firstData.fields.items[i].name == 'index') || (firstData.fields.items[i].name == 'id'))
						continue;
					var crtFieldName = firstData.fields.items[i].name;
					obj.data[crtFieldName] = "";
					for (j = 0; j < this.manualDefGrid.getStore().getCount(); ++j)
					{
						if (j > 0)
							obj.data[crtFieldName] += ', ';
						obj.data[crtFieldName] += this.manualDefGrid.getStore().getAt(j).get(crtFieldName);
					}
				}
			}
		}
		
		return obj;
	},
	
	setTableDefinition : function(tableDef)
	{
		this.tableDefTypeCombo.setValue(tableDef['tableDefType']);
		this.channelsDefTypeCombo.setValue(tableDef['channelsDefType']);
		this.nameField.setValue(tableDef['tableName']);
		this.unitsField.setValue(tableDef['tableUnits']);
		this.selectTableDefType(tableDef['tableDefType']);
		this.loadManualGridData(tableDef['channelsDefType'], tableDef['data']);
		this.loadSelectData(tableDef['data']);
	}
});