/*
 *  Copyright 2015 Anyware Services
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 *@private
 * Class handling the select values dialog box
 */
Ext.define('Ametys.plugins.forms.content.SelectValuesBox', {

	singleton: true,
	
	/**
	 * @private
	 * @property {Function} _cbFn the callback function used when the dialog box closes
	 */
	
    /**
     * @private
     * @property {Boolean} _costColumn Is cost column active?
     */
    
	/**
	 * @private
	 * @property {Ext.grid.Panel} _grid the grid panel of the dialog box
	 */
	
	/**
	 * @private
	 * @property {Ametys.window.DialogBox} _box the dialog box
	 */
	
	/**
	 * Create the select values dialog box.
	 * @param {String} valuesAsString the values of the form under the form of a string
	 * @param {Function} callback the callback function to invoke when the select values process is over
     * @param {Boolean} [costColumn=false] When true disply a third column to fill cost
	 */
	create: function(valuesAsString, callback, costColumn)
	{
		this._cbFn = callback;
        this._costColumn = costColumn;
		
		this._initialize();
		
        this._grid.getColumns()[2][costColumn ? 'show' : 'hide']();
        
		this._box.show();
		this._load(valuesAsString);
	},
	
	/**
	 * Load the values in the form
	 * @param {String} valuesAsString the form's values under the form of a string
	 */
	_load: function(valuesAsString)
	{
		valuesAsString = valuesAsString.replace(/\r/g, '');
		
		var data = [];

		if (valuesAsString != '')
		{
			var values = valuesAsString.split('\n');
			for (var i = 0; i < values.length; i++)
			{
                var vs = values[i].split(";");
                
				data.push([vs[0], vs.length > 1 ? vs[1] : '', vs.length > 2 ? parseFloat(vs[2]) || 0 : 0]);
			}
		}
		
		this._grid.getStore().loadData(data, false);
		
		if (data.length > 0)
		{
			this._grid.getSelectionModel().select(0);
			this._grid.getView().focusRow(0);
		}
	},
	
	/**
	 * Initialize the box and its grid panel
	 */
	_initialize: function()
	{
		if (this._box != null)
		{
			return;
		}
		
		var me = this;
		
		this._grid = Ext.create('Ext.grid.Panel', 
		{
			border: false,
			scrollable: true,
			
			store: Ext.create('Ext.data.ArrayStore', 
			{
				fields: ['label', 'value', 'cost']
			}),
			
			selModel: 'cellmodel',
			
	        plugins: {
	        	ptype: 'cellediting',
	        	clicksToEdit: 2
	        },

	        columns: [
		        {header: "{{i18n PLUGINS_FORMS_FORMS_EDITOR_VALUE_SELECT_BOX_GRID_COL_LABEL}}", width: 180, sortable: false, dataIndex: 'label', hideable: false, editor: Ext.create('Ext.form.field.Text', { allowBlank: false, selectOnFocus: true, regex: /^[^;]*$/ })},
		        {header: "{{i18n PLUGINS_FORMS_FORMS_EDITOR_VALUE_SELECT_BOX_GRID_COL_VALUE}}", flex:1, sortable: false, dataIndex: 'value', hideable: false, editor: Ext.create('Ext.form.field.Text', { allowBlank: true, selectOnFocus: true, regex: /^[^;]*$/ })},
                {header: "{{i18n PLUGINS_FORMS_FORMS_EDITOR_VALUE_SELECT_BOX_GRID_COL_COST}}", flex:1, sortable: false, dataIndex: 'cost', hideable: false, editor: Ext.create('Ext.form.field.Number', { allowBlank: true, selectOnFocus: true })}
	        ],
            columnLines: true,
            enableColumnMove: false, // we hide column by index...
          
             viewConfig: {
         	     forceFit: true
             },
          
             // inline toolbars
             bbar:
      	     [
                  {
                	  xtype: 'button',
                  	  flex: 0.5,
                	  text: "{{i18n PLUGINS_FORMS_FORMS_EDITOR_VALUE_SELECT_BOX_GRID_ACTION_ADD_LABEL}}",
                	  tooltip: "{{i18n PLUGINS_FORMS_FORMS_EDITOR_VALUE_SELECT_BOX_GRID_ACTION_ADD_DESCRIPTION}}",
                	  handler: Ext.bind(this._add, this)
                  },
                  '-',
                  {
                	  xtype: 'button',
                	  itemId: 'removeButton',
                	  flex: 0.5,
                	  text: "{{i18n PLUGINS_FORMS_FORMS_EDITOR_VALUE_SELECT_BOX_GRID_ACTION_DEL_LABEL}}",
                	  tooltip: "{{i18n PLUGINS_FORMS_FORMS_EDITOR_VALUE_SELECT_BOX_GRID_ACTION_DEL_DESCRIPTION}}",
                	  disabled: true,
                	  handler: Ext.bind(this._remove, this),
                	  
                  }
              ],
              
  	       listeners: {
	        	'selectionchange': Ext.bind(this._onSelectionChange, this),
	        	'edit': function(editor, context) {
	        		context.record.commit();
	        	}
	        }
		});
		
		this._box = Ext.create('Ametys.window.DialogBox', 
		{
			title: "{{i18n PLUGINS_FORMS_FORMS_EDITOR_VALUE_SELECT_BOX_LABEL}}",
			icon: Ametys.getPluginResourcesPrefix('forms') + '/img/edition/select_values_16.png',
			
			width: 475,
			height: 395,
			
			cls: 'ametys',
			layout: 'fit',
			
			items: [ this._grid ],
			
			defaultFocus: this._grid,
			closeAction: 'hide',
			
			referenceHolder: true,
			defaultButton: 'validate', 
			
			buttons: 
			[ 
	           {
	        	   reference: 'validate',
	        	   text : "{{i18n PLUGINS_FORMS_FORMS_EDITOR_VALUE_SELECT_BOX_OK}}",
	        	   handler: function() 
	        	   { 
	        		   var newValue = "";
	        		   
	        		   var store = me._grid.getStore()
	        		   
	        		   for (var i = 0; i < store.getCount(); i++)
	        		   {
	        			   if (i != 0)
	        			   {
	        				   newValue += '\n';
	        			   }
	        			   newValue += store.getAt(i).get('label');
        				   newValue += ";" + (store.getAt(i).get('value') || ''); 
	        			   
                           if (me._costColumn)
                           {
                               newValue += ";" + (store.getAt(i).get('cost') || 0); 
                           }
	        		   }
	        		   
	        		   if (me._cbFn(newValue) != false)
	        		   {
	        			   me._box.hide();
	        		   }
	        	   } 
	           }, 
	           {
	        	   text : "{{i18n PLUGINS_FORMS_FORMS_EDITOR_VALUE_SELECT_BOX_CANCEL}}",
	        	   handler: function() 
	        	   { 
	        		   me._box.hide(); 
	        	   } 
	           }
           ]
		});
	},
	
 	
	/**
	 * Add a value in the grid's store. Starts the edition of a new value
	 */
	_add: function()
	{
 		var store = this._grid.getStore(),
			sm = this._grid.getSelectionModel(),
			pos;
			
		if (sm.hasSelection())
		{
			pos = {row: sm.getPosition().rowIdx + 1, column: 0};
		}
		else
		{
			pos = {row: store.getCount(), column: 0};
		}
		
		var record = Ext.create('Ext.data.Record', 
		{
			label: "{{i18n PLUGINS_FORMS_FORMS_EDITOR_VALUE_SELECT_BOX_GRID_ACTION_ADD_DEFAULTLABEL}}", 
			value: "{{i18n PLUGINS_FORMS_FORMS_EDITOR_VALUE_SELECT_BOX_GRID_ACTION_ADD_DEFAULTVALUE}}",
            cost: this._costColumn ? null : 0
		}); 

		store.insert(pos.row, [record]);
 		this._grid.editingPlugin.startEditByPosition(pos);
	},
	
	/**
	 * Remove the selected record from the grid's store
	 */
	_remove: function()
	{
		var store = this._grid.getStore();
		var sm = this._grid.getSelectionModel();
		
		if (sm.hasSelection())
		{
			store.remove(sm.getSelection());
		}
	},
	
	/**
	 * Function invoked when a grid record is selected
	 */
	_onSelectionChange: function()
	{
		var sm = this._grid.getSelectionModel();
		this._grid.down('#removeButton').setDisabled(!sm.hasSelection());
	}
});