/*
 *  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.
 */
 
/**
 * Helper for creating or editing a CHOICE question.
 */
Ext.define('Ametys.plugins.survey.question.InputChoicesDialog', {
	singleton: true,
 	
 	/**
 	 * @private
 	 * @property {String} _mode Can be 'new or 'edit'.
 	 */
 	
 	/**
 	 * @private
 	 * @property {Ametys.window.DialogBox} _box The dialog box for creating/editing a page.
 	 */
 	 
 	/**
 	 * @private
 	 * @property {Ext.form.Panel} _formPanel The form panel of the dialog box.
 	 */

	/**
 	 * @private
 	 * @property {Ext.grid.Panel} _grid The grid containing the input choices.
 	 */
 	 
 	 /**
 	  * @private
 	  * @property {Boolean} _initialized True if the dialog box is initialized.
 	  */
	
	/**
 	  * @private
 	  * @property {Boolean} _modifiable True if the choices can be removed.
 	  */
 	
	/**
	 * Open the dialog to create or edit a question
	 * @param {Object} config The configuration object
	 * @param {Ametys.message.MessageTarget} config.target If 'new' mode, the parent target. If 'edit' mode, the target to edit.
	 * @param {String} [config.mode=new] The mode: 'new' for creation or 'edit' for edition
	 */
 	open: function (config)
 	{
 		this._mode = config.mode || 'new';
 		this._modifiable = true;
		
		this._delayedInitialize();
		
		this._initForm (config.target);
 	},
 	
 	/**
	 * @private
	 * Creates the dialog box
	 */
	_delayedInitialize: function ()
	{
		if (!this._initialized)
		{
			this._formPanel = this._createFormPanel();
			this._grid = this._createGrid();
			
			this._box = Ext.create('Ametys.window.DialogBox', {
				title: "{{i18n PLUGINS_SURVEY_QUESTION_VALUE_SELECT_BOX_LABEL}}",
	            iconCls: 'ametysicon-drop-down-list',
	            
	            width: 550,
		        scrollable: false,
		        
	            items: [this._formPanel, this._grid],
	            
	            closeAction: 'hide',
	            
	            referenceHolder: true,
	            defaultButton: 'validate',
	            defaultFocus: 'label', 
	            selectDefaultFocus: true,
	            
	            buttons: [{
	            	reference: 'validate',
	                text: "{{i18n PLUGINS_SURVEY_QUESTION_VALUE_SELECT_BOX_OK}}",
	                handler: Ext.bind(this._validate, this)
	            }, {
	                text: "{{i18n PLUGINS_SURVEY_QUESTION_VALUE_SELECT_BOX_CANCEL}}",
	                handler: Ext.bind(this._cancel, this)
	            }]    
			});
			
			this._initialized = true;
		}
	},
	
	/**
    * @private
    * Handler for the 'ok' button of the dialog box
    */
    _validate: function ()
    {
        var form = this._formPanel.getForm();
        if (!form.isValid())
        {
        	return;
        }
        
        var values = form.getValues();
        values.type = values.multiple ? 'MULTIPLE_CHOICE' : 'SINGLE_CHOICE';
        
        var options = {};
        
        this._grid.getStore().getData().each (function (record) {
        	options[record.get('label')] = record.get('value');
        });
        
        values.options = Ext.JSON.encode(options);
 		
 		if (this._mode == 'new')
 		{
 			var params = [values];
 			Ametys.cms.survey.QuestionDAO.createQuestion(params, this._validateCb, {scope: this} );
 		}
 		else
 		{
 			var id = form.findField('id').getValue();
 			
 			var params = [values];
 			Ametys.cms.survey.QuestionDAO.editQuestion(params, this._validateCb, {scope: this} );
 		}
    },
    
    /**
     * Callback function called after creation or edition process
     * @param {Object} response The server response
     * @private
     */
    _validateCb: function (response)
    {
    	if (!response['error'])
    	{
    		this._box.close();
    	}
    },
    
    /**
     * @private
     * Callback for the "cancel" button of the dialog. Close the dialog.
     */
    _cancel: function ()
    {
        this._box.close();
    },
 	
 	/**
 	 * @private
 	 * Initializes the form with some optional values.
 	 * @param {Ametys.message.MessageTarget} target If 'new' mode, the parent target. If 'edit' mode, the target to edit.
 	 */
	_initForm: function (target)
 	{
 		var form = this._formPanel.getForm();
		form.reset();
		this._grid.getStore().removeAll();
 		
 		if (this._mode === "new") 
        {
        	form.findField('id').setValue('');
 			form.findField('pageId').setValue(target.getParameters().id);
 			
 			form.findField('label').setValue("{{i18n PLUGINS_SURVEY_DIALOG_QUESTION_LABEL_DEFAULT}}");
			form.findField('title').setValue('');
			form.findField('title').clearInvalid();
			form.findField('mandatory').setValue(false);
			form.findField('multiple').setValue(false);
			form.findField('otherOption').setValue(false);
			form.findField('otherOption').setDisabled(false);
			form.findField('picture-alternative').setValue();
			form.findField('picture').setValue();
			
			this._grid.down('#addButton').setDisabled(false);
			
			this._box.show();
        }
 		else
 		{
 			form.findField('id').setValue(target.getParameters().id);
 			form.findField('pageId').setValue('');
 			
 			Ametys.cms.survey.QuestionDAO.getQuestion([target.getParameters().id], this._setValues, {scope: this});
 		}
 	},
 	
 	/**
 	 * Fill the form with some values.
 	 * @param {Object} data The question.
 	 * @private
 	 */
 	_setValues: function(data)
 	{
 		var form = this._formPanel.getForm();
 		
 		this._modifiable = data.validated == "false";
 		
	    form.findField('label').setValue(data.label);
	    form.findField('title').setValue(data.title);
	    form.findField('mandatory').setValue(data.mandatory == 'true');
	    form.findField('multiple').setValue(data.type == 'MULTIPLE_CHOICE');
		form.findField('otherOption').setValue(data.otherOption == 'true');
		form.findField('otherOption').setDisabled(!this._modifiable);
		
		form.findField('picture-alternative').setValue(data.pictureAlternative);
	    
	    if (!Ext.Object.isEmpty(data.picture))
    	{
		    data.picture.id = 'untouched';
		    form.findField('picture').setValue(data.picture);
    	}
	    else
	    {
	    	form.findField('picture').setValue();
	    }
	    
		this._loadGridStore(data.options);
		this._grid.down('#addButton').setDisabled(!this._modifiable);
		
		this._box.show();
 	},
 	
 	/**
 	 * Fill the grid with some values.
 	 * @param {Object} options The options to add in the grid.
 	 */
 	_loadGridStore: function(options)
 	{
 		var store = this._grid.getStore();
 		for (var key in options)
 		{
 			store.add({
 				label: options[key], 
 				value: key
 			});
 		}
 	},
 	
 	/**
 	 * Creates the form panel of this dialog box.
 	 * @return {Ext.form.Panel} The form panel
 	 * @private
 	 */
 	_createFormPanel: function()
 	{
 		var formPanel = Ext.create('Ext.form.Panel', {
	        defaultType: 'textfield',
	        defaults: {
	        	cls: 'ametys',
	        	labelSeparator: '',
	        	labelAlign: 'right',
	        	labelWidth: 110,
	        	width: '100%',
	        	msgTarget: 'side'
	        },
	        
	        border: false,
	        scrollable: true,
	        
	        items: [
		        {
		        	xtype: 'hidden',
		        	name: 'id'
		        },
		        {
		        	xtype: 'hidden',
		        	name: 'pageId'
		        },
		        {
		        	itemId: 'label',
		        	name: 'label',
		        	fieldLabel: "{{i18n PLUGINS_SURVEY_DIALOG_QUESTION_LABEL}}",
	                ametysDescription: "{{i18n PLUGINS_SURVEY_DIALOG_QUESTION_LABEL_DESC}}",
	                allowBlank: false,
	                maxLength: 20
		        },
		        {
		        	name: 'title',
	                fieldLabel: "{{i18n PLUGINS_SURVEY_DIALOG_QUESTION_TITLE}}",
	                ametysDescription: "{{i18n PLUGINS_SURVEY_DIALOG_QUESTION_TITLE_DESC}}",
	                allowBlank: false
		        },
		        {
                    xtype: 'edition.file',
                    name: 'picture',
                    allowSources: [Ametys.form.widget.File.External.SOURCE, Ametys.cms.widget.File.Resource.SOURCE],
                    filter: Ametys.form.widget.File.IMAGE_FILTER,
                    fieldLabel: "{{i18n PLUGINS_SURVEY_DIALOG_QUESTION_PICTURE_LABEL}}",
                    ametysDescription: "{{i18n PLUGINS_SURVEY_DIALOG_QUESTION_PICTURE_DESC}}"
                },
                {
                    xtype: 'textfield',
                    name: 'picture-alternative',
                    fieldLabel: "{{i18n PLUGINS_SURVEY_DIALOG_QUESTION_PICTURE_ALT_LABEL}}",
                    ametysDescription: "{{i18n PLUGINS_SURVEY_DIALOG_QUESTION_PICTURE_ALT_DESC}}"
                },
		        {
		        	xtype: 'checkbox',
		        	name: 'mandatory',
		        	fieldLabel: ' ',
	                boxLabel: "{{i18n PLUGINS_SURVEY_DIALOG_QUESTION_MANDATORY}}",
	                ametysDescription: "{{i18n PLUGINS_SURVEY_DIALOG_QUESTION_MANDATORY_DESC}}",
	                inputValue: 'true',
	                checked: false
		        },
		        {
		        	xtype: 'checkbox',
		        	name: 'multiple',
		        	fieldLabel: ' ',
	                boxLabel: "{{i18n PLUGINS_SURVEY_DIALOG_QUESTION_MULTIPLE}}",
	                ametysDescription: "{{i18n PLUGINS_SURVEY_DIALOG_QUESTION_MULTIPLE_DESC}}",
	                inputValue: 'true',
	                checked: false
		        },
		        {
		        	xtype: 'checkbox',
		        	name: 'otherOption',
		        	fieldLabel: ' ',
	                boxLabel: "{{i18n PLUGINS_SURVEY_DIALOG_QUESTION_OTHER_OPTION}}",
	                ametysDescription: "{{i18n PLUGINS_SURVEY_DIALOG_QUESTION_OTHER_OPTION_DESC}}",
	                inputValue: 'true',
	                checked: false
		        }
	        ]
        	
 		});
 		
 		return formPanel;
 	},
 	
 	/**
 	 * Creates the bottom grid of this dialog box.
 	 * @return {Ext.grid.Panel} The grid
 	 * @private
 	 */
 	_createGrid: function()
 	{
 		var grid = Ext.create('Ext.grid.Panel', {
 			height: 250,
 			border: false,
	        scrollable: true,
	        
	        store: {
	        	fields: ['label', 'value'],
	        	trackRemoved: false
	        },
	        
	        stateful: true,
     		stateId: this.self.getName() + "$grid",
	        columns: [
            {
	             stateId: 'grid-column-label', 
	             header: "{{i18n PLUGINS_SURVEY_QUESTION_VALUE_SELECT_BOX_GRID_COL_LABEL}}",
	             menuDisabled: true,
	             sortable: false, 
	             dataIndex: 'label', 
	             editor: {
	            	xtype: 'textfield',
	            	allowBlank: false,
	            	selectOnFocus: true
	            } 
            }],
	        columnLines: true,
	        forceFit: true,
	        selModel: 'cellmodel',
	        plugins: {
	        	ptype: 'cellediting',
	        	clicksToEdit: 2
	        },
	        
	        bbar: [
		        {
		        	xtype: 'button',
		        	itemId: 'addButton',
		        	width: 305,
		        	text: "{{i18n PLUGINS_SURVEY_QUESTION_VALUE_SELECT_BOX_GRID_ACTION_ADD_LABEL}}",
		        	tooltip: "{{i18n PLUGINS_SURVEY_QUESTION_VALUE_SELECT_BOX_GRID_ACTION_ADD_DESCRIPTION}}",
		        	handler: Ext.bind(this._add, this)
		        },
		        '-',
		        {
		        	xtype: 'button',
		        	itemId: 'removeButton',
		        	width: 200,
		        	text: "{{i18n PLUGINS_SURVEY_QUESTION_VALUE_SELECT_BOX_GRID_ACTION_DEL_LABEL}}",
		        	tooltip: "{{i18n PLUGINS_SURVEY_QUESTION_VALUE_SELECT_BOX_GRID_ACTION_DEL_DESCRIPTION}}",
		        	handler: Ext.bind(this._remove, this),
		        	disabled: true
		        }
	        ],
	        
	        listeners: {
	        	'selectionchange': Ext.bind(this._onSelectionChange, this),
	        	'edit': function(editor, context) {
	        		context.record.commit();
	        	}
	        }
 		});
 		
 		return grid;
 	},
 	
 	/**
 	 * Listener when the selection in the grid has changed.
 	 * @private
 	 */
 	_onSelectionChange: function()
 	{
 		var sm = this._grid.getSelectionModel();
 		var setEnable = sm.hasSelection() && this._modifiable;
 		this._grid.down('#removeButton').setDisabled(!setEnable);
 	},
 	
 	/**
 	 * Adds a new choice to the grid, and starts the edition of its name.
 	 * @private
 	 */
 	_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};
 		}
 		
 		store.insert(pos.row, {
 			label: "{{i18n PLUGINS_SURVEY_QUESTION_VALUE_SELECT_BOX_GRID_ACTION_ADD_DEFAULTLABEL}}", 
 			value: ''
 		});
 		this._grid.editingPlugin.startEditByPosition(pos);
 	},
 	
 	/**
 	 * Removes the selected record of the grid.
 	 * @private
 	 */
 	_remove: function()
 	{
 		var store = this._grid.getStore(),
 			sm = this._grid.getSelectionModel();
 		
 		if (sm.hasSelection())
 		{
 			store.remove(sm.getSelection());
 		}
 	}
 	
 	
});