/**
  * Project      :  AMDA-NG
  * Name         : ParamEditorPlugin.js
  * @plugin 	  amdaUI.ParamEditorPlugin
  * @extends 	  Ext.util.Observable 
  * @ptype 	 paramEditorPlugin	  
  * @brief		 
  * @author  
  * @version $Id: ParamEditorPlugin.js 2259 2014-04-02 12:22:26Z elena $
  ********************************************************************************
  *    FT Id     :   Date   : Name - Description
  *******************************************************************************
  *  :          
  */


Ext.define('amdaUI.ParamEditorPlugin', {
	extend: 'Ext.AbstractPlugin',
	alias: 'plugin.paramEditorPlugin',
	
	requires : [
	   'amdaModel.ArgGroups'
	],
 	
	titles: null,
	
	y2axe: null,
	win: null,
	// calculate number of fieldsets added - to avoid rendering problem
	fieldsetNumber: 0,
	height : 150,
	
	confCombo : { width: 150, 
		      labelAlign: 'top',
		      margin: '5 10 0 0',								      
		      queryMode: 'local',
		      editable: false, 						 
		      displayField: 'value' 
	},
		
	confField : { width: 150, 
		      labelAlign: 'top',
		      allowDecimals : false,
		      hideTrigger: true,
		      margin : '5 10 0 0'
	},
	
	configFS : {layout:'column'},
	
	 
	init: function(cmp) {
	    this.hostCmp = cmp;   
	    this.hostCmp.on('openParamEditor', this.onOpen, this);
	    
	    if (!this.titles) {
		this.titles = new Ext.util.MixedCollection();
		this.titles.addAll([{ name: 'xTitle', label:  'X Title' },
				    { name: 'yTitle', label:  'Y Title' }]);		   
	    } 
	    if (!this.y2axe) {
		this.y2axe = new Ext.util.MixedCollection();
		this.y2axe.addAll([{ xtype: 'textfield', name: 'y2Title', label:  'Y2 Title'},
				   { xtype: 'numberfield', name: 'y2RangeMin', label: 'Y2min'},
				   { xtype: 'numberfield', name: 'y2RangeMax', label: 'Y2max'}]);	   
	    }	    	   
	},
	
	apply: function() { 
	    var args = this.form.getForm().getValues(this.record.isLeaf());
	    
	    if (this.record.isLeaf()) {	
                //arguments for some special parameters
	          if (this.record.get('needsArgs')) {
			var argsDownload = this.form.getForm().getValues(); 
			this.record.set('downloadParamArgs',argsDownload);
		  }
		  this.record.set('paramArgs',args);		 
	    }
	    else {
	         var panelArgs = ''; 
	         if(args.xTitle) {
		            this.record.set('xTitle', args.xTitle);
			    panelArgs += 'Xtitle';
		 }
		 if(args.yTitle) {
		   this.record.set('y1Title', args.yTitle);
		   panelArgs += ' Ytitle';
		 }
	       this.record.set('panelArgs', panelArgs);
	    }
	    this.win.close();
	}, 
	
	reset: function() {
	    this.form.getForm().reset();
	}, 

	onOpen: function(record) {
	 
		var str = record.get('paramArgs');
		if ( str && str !== 'select...')
		{
			this.values = []; 
			var arr = str.split('&');
			if (arr.length > 1)
			{
				this.values = [];
				Ext.each(arr, function(item)
						{
							var obj = item.split('=');		
							this.values.push({ id : obj[0], value: obj[1] });
						}, this);	   
		    }
		    else
		    {
		    	var obj = str.split('=');		     
		    	this.values.push({id : obj[0], value: obj[1]});
		    } 
		} 
		if ( str && str == 'select...')
			this.values = null;
	   
		if (this.win)
			this.win.close(); 	   		

		this.record = record;
                //
		this.paramId = record.get('name');	
		this.getFormConfig(record.isLeaf(), function(items)
				{
					this.win = new Ext.Window({			
						id: 'parameditor-win-'+this.hostCmp.id, 
						width: 550, 
						height: this.height,
						x: 0, y: 0,
						baseCls:'x-panel',	 
						title: 'Select Arguments for ' + this.paramId,
						layout: 'fit',
						constrain: true,
						ghost: false,
						renderTo: this.hostCmp.ownerCt.getId(),
						items: items,
						listeners: {
							scope: this,			    
							beforeclose: function(){			      			     
								Ext.PluginManager.unregister(this);				
							},								
							show: function(){
								if (this.values) { 
									//TODO defer - if not - values are not set - which event to use?
									//Ext.Function.defer(function(){
									this.form.getForm().setValues(this.values);
									
								    
									//}, 500, this); 				   
								}
								this.form.doLayout();
							} 
						},
						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);
					        }
					    }
					});
			
					if (this.fieldsetNumber > 0) {
						if (this.fieldsetNumber > 1) this.win.setHeight(this.height *  this.fieldsetNumber);
						this.win.show(); 
						Ext.PluginManager.register(this);
						this.fieldsetNumber = 0;
					} else {
						myDesktopApp.infoMsg("This parameter has no arguments");
		       			this.values = null;
		     		}
			
				});    
	},
	
	loadArgsStore: function(items,successfn)
	{
		var argStore = Ext.create('Ext.data.Store',{model: 'amdaModel.ArgGroups'});
		//is sent to server to find parameter XML description
		argStore.getProxy().extraParams.paramID = this.paramId;
		argStore.getProxy().extraParams.application = 'plot';
		
		argStore.load({
			scope   : this,
			callback: function(records, operation, success) {			  
			if (success && records[0].get('group') != 'nok') {
				
				this.simpleGroup = false;
				this.settingGroup = false;
				
				argStore.each(function(grp){
					
					var args = grp.args();
					var units = grp.get('units');
					
					
					if (grp.get('groupE') || grp.get('groupEmulti')) {				   				  				  
						
						var fieldsetSpectro = new Ext.form.FieldSet({ layout:'hbox', height: 25 });
						//plot type radio group	    
						var radioGroup = new Ext.form.RadioGroup({ layout :  'hbox', 
							items: [
							        {boxLabel: 'Spectrogram', name: 'plot', inputValue: 'spectro', checked: true,
							        	listeners: {
							        	scope : this,
							        	change: function (cb, nv, ov) {
							        		if (nv == ov) return;
							        		var fs = Ext.getCmp('energyFieldSet');
							        		if (nv) 
							        			fs.disable();												     
							        		else  
							        			fs.enable(); 
							        		} 
							        	}
							        },
							        {boxLabel: 'Time Serie', name: 'plot', inputValue: 'serie', margin : '0 0 0 20' }						 
							]});			           			 	    
					     
						fieldsetSpectro.add(radioGroup);
					
					    var isMulti = false;
					    var argsN = args.count();
					    var argMin  = args.first();
					    var argMax = args.getAt(argsN-1);

					    var title = grp.get('groupE') || grp.get('groupEmulti');
					    if (grp.get('groupEmulti'))  isMulti = true;
						    
					    var fieldset = new Ext.form.FieldSet({layout:'hbox', height: 70, id : 'energyFieldSet'});
					     
					    var suffix = 'Min';
					    var argValue = argMin;
					    
					    for (var i = 0; i < 2; i++) {
					          var label = title + suffix;				  
						  var fieldlabel = label + ' ' +units;
						  
						  if (isMulti){
							var config = {name: label, fieldLabel: fieldlabel, minValue: argValue, maxValue: argMax, value: argValue.get('value')};					  
							Ext.applyIf(config, this.confField);				    
							var combo = new Ext.form.field.Number(config); 
						  }					
						  else {					        
							var config = {name: label, fieldLabel: fieldlabel, store: args,  value: argValue};
							this.confCombo.valueField = 'value';
							Ext.applyIf(config, this.confCombo);				    
							var combo = new Ext.form.field.ComboBox(config);						
						  }
						  fieldset.add(combo);
						  
						  var suffix = 'Max';   
						  argValue = argMax;
						  
					    } 
								    
                                            fieldset.disable();				    
                                            this.form.add(fieldsetSpectro);
						
					    this.fieldsetNumber++;
					     
					    this.form.add(fieldset);
					
					  }  
					  else 
					  {  
					      var title =  grp.get('group') || grp.get('groupS');
					     
                                                if (title)
                                                {
                                                    if (units) 
                                                            label = title + ' ' + units;				       
                                                    else
                                                            label = title;
					    	  
                                                    var argsN   = args.count();
                                                    var argMin  = args.first();
					    	  
					    	  if (argsN >  1)
					    	  {
					    	   //combo
					    	    var config = 
					    	    	{
					    	    		name         : title,
					    	    		fieldLabel   : label, 
					    	    		displayField : 'value',
                                                                valueField   : 'arg',
					    	    		store        : args, 
					    	    		value        : args.first().get('arg')
					    	    	};
					    	    
					    	    Ext.applyIf(config, this.confCombo);
					    	 
					    	    var newField = new Ext.form.field.ComboBox(config);
					    	  }
					    	  else if (argMin && argMin.get('value'))
					    	  {
					    	   
                                                    var config = {name: title, fieldLabel: label, value: argMin.get('value')};					  
                                                    Ext.applyIf(config, this.confField);
                                                    
                                                    //text
                                                    if (isNaN(parseInt(argMin.get('value')))) {
                                                            var newField = new Ext.form.field.Text(config);
                                                            newField.setReadOnly(true);
                                                    }
                                                    //number
                                                    else
                                                            var newField = new Ext.form.field.Number(config); 
					    	  }
					    	  else
					    		  return;
						  
					    	  if (grp.get('group'))
					    	  {					   
					    		  if (!this.simpleGroup)
                                                                this.fieldsetSimple = new Ext.form.FieldSet(this.configFS);	
					    		  this.simpleGroup = true;
					    		  this.fieldsetSimple.add(newField);				    
					    	  }
					    	  else 
					    	  {					  
					    		  if (!this.settingGroup)
					    			  this.fieldsetSetting = new Ext.form.FieldSet(this.configFS);
					    		  this.settingGroup = true;
					    		  this.fieldsetSetting.add(newField);   
					    	  }
					      }			  
				     
					  	}
				      },  this); 
				       
				    this.fieldsetNumber++;
			            
			            if (this.simpleGroup) this.form.add(this.fieldsetSimple);
				    if (this.settingGroup) this.form.add(this.fieldsetSetting);
				    
				    
				    if (successfn)
	   					successfn.call(this,items);
				  }
				  else {			    
					  myDesktopApp.errorMsg("Cannot load parameter arguments!");
				  } 			 
			      }
			      
			    });
	},
	
	getFormConfig: function(isParam,successfn){
	   
	   this.form = new Ext.form.Panel( {
	    	frame: true, buttonAlign: 'left', autoScroll: true,
	    	layout: { type: 'vbox', align : 'stretch', autoSize: true},
		 fbar: [
		  {
		      text: 'Apply',
		      scope : this,
		      handler: this.apply
		  },
		   {
		      text: 'Reset',
		      scope : this,		       
		      handler: this.reset 
		   } ]
		});
	      
	   // Get parameter arguments from Server
	      if (isParam)
	    	  this.loadArgsStore(this.form,successfn);
	     // Additional Panel arguments 
	      else {
		   var fieldset = new Ext.form.FieldSet(this.configFS);
		   var isDisabled, value;
		   var plotType = this.record.get('plotType');
		    
		   this.titles.each(function(item){		      
		      isDisabled = (plotType == 'TIME' && item['label'] == 'X Title');		      
		      value = isDisabled ? 'Time' : this.record.get(item['name']);
		      var textField = new Ext.form.field.Text({
			  width: 150, 
			  labelAlign: 'top',
			  margin: '5 10 0 0',
			  name: item['name'],
			  value: value,
			  disabled: isDisabled,
			  fieldLabel: item['label']		
			});		      
			fieldset.add(textField);			 
		  }, this);
		  this.fieldsetNumber++;
		  this.form.add(fieldset);
		  
		  var y2disable = this.record.childNodes.length == 1; 
		  var fieldsetY = new Ext.form.FieldSet(this.configFS);		  
		  this.y2axe.each(function(item){
		      var textField = new Ext.form.field.Text({
			  width: 100, 
			  labelAlign: 'top',
			  margin: '5 10 0 0',
			  name: item['name'],
			  fieldLabel: item['label'],
			  disabled: y2disable
			});		      
			fieldsetY.add(textField);
		  }, this);
		   this.fieldsetNumber++;
		   this.form.add(fieldsetY);
		   if (successfn)
			   successfn.call(this,this.form);
	      }	 
	    return this.form;
	}    
		
});