/**
 * Project       AMDA-NG
 * Name          CatalogVisuScatter.js
 * @class 	   amdaUI.CatalogVisuScatter
 * @extends      Ext.container.Container
 * @brief	   Scatter Visualization Module UI definition (View)
 * @author 	  elena
 */

Ext.define('amdaUI.CatalogVisuScatter', {
	extend: 'Ext.form.Panel',
	alias: 'widget.panelCatalogVisuScatter',
	requires: [
		'amdaPlotObj.PlotObjectConfig',
		'amdaPlotComp.PlotColorPicker'
	],

	availableSymbolsTypes: [
		{ 'key': 'circle', 'value': 'Dot' },
		{ 'key': 'cross-open', 'value': 'Plus' },
		{ 'key': 'circle-open', 'value': 'Circle' },
		{ 'key': 'x-open', 'value': 'Crux' },
		{ 'key': 'square-open', 'value': 'Square' },
		{ 'key': 'triangle-up-open', 'value': 'Triangle Up' },
		{ 'key': 'triangle-down-open', 'value': 'Triangle Down' },
		{ 'key': 'triangle-left-open', 'value': 'Triangle Left' },
		{ 'key': 'triangle-right-open', 'value': 'Triangle Right' },
		{ 'key': 'circle-cross-open', 'value': 'Crux in circle' },
		{ 'key': 'circle-open-dot', 'value': 'Dot in circle' },
		{ 'key': 'diamond', 'value': 'Diamond' },
		{ 'key': 'star-open', 'value': 'Star' },
		{ 'key': 'hexagram-open', 'value': 'Hexagram' },
		{ 'key': 'square', 'value': 'Full square' },
		{ 'key': 'star', 'value': 'Full star' }
	],

	constructor: function(config) {
		this.init(config);
		this.callParent(arguments);
	},

  getChartConfig: function(catalogStore, isColorBar=true) {
    var plotTypeField = Ext.getCmp('visu-scatter-type');
    var plotType = plotTypeField.getValue();

    var plotColorField = Ext.getCmp('visu-scatter-color');
    var plotColor=plotColorField.ownerCt.colorDisplayer.value;

	var plotSizeField = Ext.getCmp('visu-scatter-size');
	var plotSize = plotSizeField.getValue();

	var plotSymbolField = Ext.getCmp('visu-scatter-symbol');
	var plotSymbol = plotSymbolField.getValue();	

	//plotColor = plotColorField.getValue();
    var xAxisOpt = this.getAxisOptions('X');
    var yAxisOpt = this.getAxisOptions('Y');
	var zAxisOpt = this.getAxisOptions('Z');

    if ((!xAxisOpt.paramId) || (xAxisOpt.paramId == '')) {
      //myDesktopApp.errorMsg('Missing parameter selection for X axis');
      return null;
    }

    if ((!yAxisOpt.paramId) || (yAxisOpt.paramId == '')) {
      //myDesktopApp.errorMsg('Missing parameter selection for Y axis');
      return null;
    }
	if ((!zAxisOpt.paramId) || (zAxisOpt.paramId == '')) {
		//myDesktopApp.errorMsg('Missing parameter selection for Y axis');
		isColorBar= false;
	}

	var x=[];
	var y=[];
	var z=[];
	var text=[];
	catalogStore.each(function(item){
		x.push(item.get(xAxisOpt.paramId));
		y.push(item.get(yAxisOpt.paramId));
		if (isColorBar){
			if (zAxisOpt.logscale && zAxisOpt.range ){
				if (Math.log10(item.get(zAxisOpt.paramId)) >= zAxisOpt.range.min && Math.log10(item.get(zAxisOpt.paramId)) <= zAxisOpt.range.max){
					z.push(Math.log10(item.get(zAxisOpt.paramId)));
				}
				else {
					z.push(NaN);
				}
			}
			else if(zAxisOpt.logscale && !zAxisOpt.range){
				z.push(Math.log10(item.get(zAxisOpt.paramId)));
			}
			else if( !zAxisOpt.logscale && zAxisOpt.range){
				if (item.get(zAxisOpt.paramId) >= zAxisOpt.range.min && item.get(zAxisOpt.paramId) <= zAxisOpt.range.max){
					z.push(item.get(zAxisOpt.paramId));
				}
				else {
					z.push(NaN);
				}
			}
			else{
				z.push(item.get(zAxisOpt.paramId));
			}
		}
		text.push(''+item.get('start').toISOString()+'<br>'+item.get('stop').toISOString());
	});
	
	var data =[{
	x: x,
	y: y,
	mode: (plotType=='point+line') ? 'lines+markers' : 'markers',
	hovertemplate: (isColorBar) ? '(%{x},%{y},%{marker.color}) <br>%{text}<extra></extra>': null,
	text: text,
	marker:{
		color: (isColorBar) ?  z : plotColor,
		colorbar:(isColorBar) ? {
			len:0.7,
			title: (zAxisOpt.logscale) ? 'log'+'10'.sub()+'('+zAxisOpt.title+')' : zAxisOpt.title,
			titleside:'right',
			titlefont:{size:10},
		  } : null,
		colorscale: (isColorBar) ?'Jet':null,
		showscale:isColorBar,
		symbol: plotSymbol,
		size : plotSize,
	},
	type: 'scatter'}];

	var layout = {
		margin: {l: 50,r: 40, b: 40,t: 40,pad: 5},
		xaxis: {
			title: xAxisOpt.title, range: !xAxisOpt.range ? null : [xAxisOpt.range.min,xAxisOpt.range.max],
			type: xAxisOpt.logscale ? 'log' : null
		},
		yaxis: {
			title: yAxisOpt.title, range: !yAxisOpt.range ? null : [yAxisOpt.range.min,yAxisOpt.range.max],
			type: yAxisOpt.logscale ? 'log' : null
		},
		hovermode: "closest",
		hoverlabel :{ font:{size:10}}	
	};
	var result =  {data:data,layout:layout}
    return result;
  },

  getAxisOptions: function(axisName) {
    var opt = {
      paramId: '',
      title: axisName+' axis'
    };

    var axisParamField = Ext.getCmp('visu-scatter-' + axisName + '-param');
    var paramFieldId = axisParamField.getValue();
    if (paramFieldId && (paramFieldId != "")) {
      var paramField = axisParamField.getStore().getById(axisParamField.getValue());
      if (paramField) {
        opt.paramId = paramField.get('id');
				opt.title = paramField.get('name');
      }
    }

    var axisTitleField = Ext.getCmp('visu-scatter-'+axisName+'-title');
    var axisTitle = axisTitleField.getValue();
    if (axisTitle && (axisTitle != "")) {
      opt.title = axisTitle;
    }

    var axisScalingField = Ext.getCmp('visu-scatter-'+axisName+'-scaling');
	if (axisScalingField){
		var axisScaling = axisScalingField.getValue();	
	}
	if (axisScaling == 'manual') {
      var axisRangeMinField = Ext.getCmp('visu-scatter-' + axisName + '-range-min');
      var axisRangeMin = axisRangeMinField.getValue();
      var axisRangeMaxField = Ext.getCmp('visu-scatter-' + axisName + '-range-max');
      var axisRangeMax = axisRangeMaxField.getValue();
      opt.range = {
        'min' : axisRangeMin,
        'max' : axisRangeMax
      };
    }

	if (Ext.getCmp('visu-scatter-' + axisName + '-logbox')){
		opt.logscale = Ext.getCmp('visu-scatter-' + axisName + '-logbox').getValue();
	}
    return opt;
  },

	getAxisConfig: function(axisIndex, axisName, parametersStore, isColorbar = false) {
		var paramComboConfig = {
			xtype: 'combo',
			emptyText: 'select parameter',
			editable: false,
			store: parametersStore,
			queryMode: 'local',
			displayField: 'name',
			valueField: 'id',
			axisIndex: axisIndex,
      		id: 'visu-scatter-' + axisName + '-param',
			listeners:{
				change:function(){
					var isNotColorBar = Ext.getCmp('Zaxis-fieldset');
					this.visuUI.plotChart(!isNotColorBar.collapsed);
				},
				scope: this
			}
		};

		var comboRangeConfig = {
			xtype : 'combo',
			name:'scaling',
			valueField: 'scaling',
			queryMode:'local',
			store:['auto','manual'],
			forceSelection:true,
			value: 'auto',
			width: 80,
      		id: 'visu-scatter-' + axisName + '-scaling',
			listeners : {
				scope : this,
				change : function(combo, newValue, oldValue) {
					var minValue = combo.next().next();
					var maxValue  = minValue.next().next();
					var disabled = newValue == "auto";
					minValue.reset();
					maxValue.reset();
					minValue.setDisabled(disabled);
					maxValue.setDisabled(disabled);
				}
			}
		};

		var logbox={
				xtype: 'fieldcontainer',
				fieldLabel: 'Log Scale',
				defaultType: 'checkboxfield',
				items: [
					{
						name      : 'logscale',
						inputValue: false,
						id        : 'visu-scatter-' + axisName + '-logbox',
						listeners:{
						change:function(){
							var isNotColorBar = Ext.getCmp('Zaxis-fieldset');
							this.visuUI.plotChart(!isNotColorBar.collapsed);
						},
						scope: this
						}
					}
				],
		  };

		var axisRangeConfig = {
			xtype : 'fieldcontainer',
			layout: 'hbox',
			items: [
				{
					xtype:'fieldset',
					title: axisName + ' Range',
					border: false,
					layout: 'hbox',
					items: [
						comboRangeConfig,
						{
							xtype: 'splitter'
						},
						{
							xtype: 'numberfield',
							hideTrigger: true,
							width: 50,
							disabled: true,
              				id: 'visu-scatter-' + axisName + '-range-min',
							listeners:{
								change:function(){
									var isNotColorBar = Ext.getCmp('Zaxis-fieldset');
									this.visuUI.plotChart(!isNotColorBar.collapsed);
								},
								scope: this
							}
						},
						{
							xtype: 'splitter'
						},
						{
							xtype: 'numberfield',
							hideTrigger: true,
							width: 50,
							disabled: true,
             				id: 'visu-scatter-' + axisName + '-range-max',
							listeners:{
								change:function(){
									var isNotColorBar = Ext.getCmp('Zaxis-fieldset');
									this.visuUI.plotChart(!isNotColorBar.collapsed);
								},
								scope: this
							}
						},
					]
				},
			]
		};

		return {
			xtype : 'fieldset',
			id:axisName + 'axis-fieldset',
			collapsed:isColorbar,
			collapsible:true,
			checkboxToggle:isColorbar,
			checkboxName:axisName + ' axis-checkbox',
			title : axisName + ' axis',
			items : 
				[
					paramComboConfig,
					axisRangeConfig,
					logbox,
					{
						xtype: 'textfield',
						fieldLabel: axisName + ' title',
						  id: 'visu-scatter-' + axisName + '-title',
						listeners:{
							change:function(){
								var isNotColorBar = Ext.getCmp('Zaxis-fieldset');
								this.visuUI.plotChart(!isNotColorBar.collapsed);
							},
							scope: this
						},
					}
				],
			listeners: (isColorbar) ? {
				collapse:function(){
					this.visuUI.plotChart(false);
					var colorPicker = Ext.getCmp('visu-scatter-color-fieldset');
					colorPicker.show(true)
					
				},
				expand : function(combo, newValue, oldValue){
					this.visuUI.plotChart();
					var colorPicker = Ext.getCmp('visu-scatter-color-fieldset');
					colorPicker.hide(true)
				},
				scope: this
			}: null,
		};
	},

	getPlottingOptionConfig: function() {
		var plotTypeComboConfig = {
			xtype: 'combo',
			fieldLabel:'Type',
			margin:'2 2 2 2',
			emptyText: 'select plot type',
			editable: false,
			store: ['point', 'point+line'],
			queryMode: 'local',
			valueField: 'type',
			value: 'point',
      		id: 'visu-scatter-type',
			listeners : {
				scope : this,
				change : function(combo, newValue, oldValue) {
					//this.chartConfig.series[0].type = newValue;
					var isNotColorBar = Ext.getCmp('Zaxis-fieldset');
					this.visuUI.plotChart(!isNotColorBar.collapsed);
				}
			},scope: this
		};
		var colorPicker = this.addColorsPicker('visu-scatter-color', 'Color', amdaDefaultConfigs.availableColorsNew, 'standard');
		var plotThemeComboConfig = {xtype:'fieldset',
									id:'visu-scatter-color-fieldset',
									margin:'5 0 0 0',
									padding:0,
									border:false,
									items:[colorPicker],
								};
		colorPicker.add({id:'visu-scatter-color'});

		var comboStore = Ext.create('Ext.data.Store', {
			fields: [amdaPlotObj.PlotObjectConfig.fieldComboBox.key, amdaPlotObj.PlotObjectConfig.fieldComboBox.value],
			data: this.availableSymbolsTypes
		});
		var plotSymbolConfig = 
		{
			xtype: 'combo',
			store: comboStore,
			fieldLabel:'Symbol',
			editable:false,
			margin:'2 2 2 2',
			queryMode: 'local',
			displayField: 'value',
			valueField: 'key',
			value:'circle',
			id: 'visu-scatter-symbol',
			listeners: {
				scope : this,
				change : function(combo, newValue, oldValue) {
					//this.chartConfig.theme = newValue;
					var isNotColorBar = Ext.getCmp('Zaxis-fieldset');
					this.visuUI.plotChart(!isNotColorBar.collapsed);
				}
			}
		};

		var plotSizeNumber=
			{
				xtype: 'numberfield',
				layout:'hbox',
				hidden: true,
				width: 50,
				disabled: true,
				value: 5,
				id: 'visu-scatter-size'
			};
		
		var plotSizeConfig = {
					xtype: 'slider',
					fieldLabel: 'Size',
					layout:'hbox',
					margin:'2 2 2 2',
					width: 80,
					value: 5,
					increment: 1,
					minValue: 1,
					maxValue: 20,
					id: 'visu-scatter-size2',
					listeners: {
					  change: function ( slider, newValue, thumb, eOpts ) {
						var binValueField = Ext.getCmp('visu-scatter-size');
						binValueField.setValue(newValue);
					  },
					  changecomplete: function(){
						var isNotColorBar = Ext.getCmp('Zaxis-fieldset');
						this.visuUI.plotChart(!isNotColorBar.collapsed);
					  },
					  scope: this
					}
			};


		return {
			xtype : 'fieldset',
			collapsed:true,
			collapsible:true,
			layout:'fit',
			title : 'Plotting Options',
			items : [
				plotTypeComboConfig,
				plotSymbolConfig,
				plotSizeConfig,
				plotSizeNumber,
				plotThemeComboConfig,
			]
		};
	},

	addColorsPicker: function (name, label, availableColors, mode) {
		if (!mode) {
			mode = 'standard';
		}
		var me =this;
		return new amdaPlotComp.PlotColorPicker({name: name, label: label, mode: mode, colors: availableColors, onChange: function(name, newValue, oldValue) {
			var isNotColorBar = Ext.getCmp('Zaxis-fieldset');
			me.visuUI.plotChart(!isNotColorBar.collapsed);
		}});
	},

	init : function (config)
	{
		var myConf = {
			autoScroll:true,
			items: [
				this.getAxisConfig(0,'X', config.parametersStore),
				this.getAxisConfig(0,'Y', config.parametersStore),
				this.getAxisConfig(0,'Z', config.parametersStore,true),
				this.getPlottingOptionConfig()
			],
		};

		Ext.apply (this, Ext.apply(arguments, myConf));
    }
});