/*
 *  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 word definition
 */
Ext.define('Ametys.plugins.glossary.WordDefinitionDialog', {
	singleton: true,
 	
 	/**
 	 * @private
 	 * @property {Ext.form.Panel} _formPanel The form panel.
 	 */
 	
	/**
	 * Open the dialog to create or edit a word definition
	 * @param {Object} config The configuration object
	 * @param {String} config.lang lang The language for definition
	 * @param {String} [config.id] id The id of word definition. Can not null in edition mode.
	 * @param {String} [config.mode=new] The mode: 'new' for creation or 'edit' for edition
	 * @param {String} [config.word] The word. Can be null.
	 * @param {Function} [config.callback] The callback function
	 */
 	open: function (config)
 	{
 		this._mode = config.mode || 'new';
 		this._cbFn = config.callback;
		this._lang = config.lang;
		
		this._delayedInitialize();
		
		this._initForm (config);
 	},
 	
 	/**
	 * @private
	 * Creates the dialog box
	 */
	_delayedInitialize: function ()
	{
		if (!this._initialized)
		{
			this._formPanel = this._createFormPanel();
			
			this._box = Ext.create('Ametys.window.DialogBox', {
				title: "{{i18n PLUGINS_GLOSSARY_DEFINITION_ADD_TITLE}}",
	            icon: Ametys.getPluginResourcesPrefix('glossary') + '/img/glossary-16.png',
	            
	            width: 540, 
                maxHeight: 600,
		        scrollable: false,
                layout: 'fit',
	            
	            items: [this._formPanel],
	            
	            selectDefaultFocus: true,
	            defaultFocus: 'word',
	            
	            referenceHolder: true,
	            defaultButton: 'validate',

	            closeAction: 'hide',
	            
	            buttons: [{
	            	reference: 'validate',
	                text: "{{i18n PLUGINS_GLOSSARY_DEFINITION_DIALOG_OK}}",
	                handler: Ext.bind(this._validate, this)
	            }, {
	                text: "{{i18n PLUGINS_GLOSSARY_DEFINITION_DIALOG_CANCEL}}",
	                handler: Ext.bind(this._cancel, this)
	            }]    
			});
			
			this._initialized = true;
		}
		
		if (this._mode == 'new')
 		{
 			this._box.setTitle("{{i18n PLUGINS_GLOSSARY_DEFINITION_ADD_TITLE}}");
 			this._box.setIcon(Ametys.getPluginResourcesPrefix('glossary') + "/img/glossary-add-16.png");
 		}
 		else
 		{
 			this._box.setTitle("{{i18n PLUGINS_GLOSSARY_DEFINITION_EDIT_TITLE}}");
 			this._box.setIcon(Ametys.getPluginResourcesPrefix('glossary') + "/img/glossary-edit-16.png");
 		}
	},
	
	/**
    * @private
    * Handler for the 'ok' button of the dialog box
    */
    _validate: function ()
    {
        var form = this._formPanel.getForm();
        if (!form.isValid())
        {
        	return;
        }
        
        if (form.findField('word').getValue().trim() == '')
 		{
 			form.findField('word').markInvalid("{{i18n PLUGINS_GLOSSARY_DEFINITION_DIALOG_WORD_INVALID}}");
 			return;
 		}
 		if (form.findField('definition').getValue().trim() == '')
 		{
 			form.findField('definition').markInvalid("{{i18n PLUGINS_GLOSSARY_DEFINITION_DIALOG_DEFINITION_INVALID}}");
 			return;
 		}
        
        var values = form.getValues(false, false, false, true);
 		
 		if (this._mode == 'new')
 		{
 			var params = [values.word, values.variants, values.definition, values.themes, values.displayOnText, Ametys.getAppParameters().siteName, this._lang];
 			Ametys.cms.glossary.GlossaryDAO.createDefinition(params, this._validateCb, {scope: this} );
 		}
 		else
 		{
 			var id = form.findField('id').getValue();
 			
 			var params = [id, values.word, values.variants, values.definition, values.themes, values.displayOnText, Ametys.getAppParameters().siteName, this._lang];
 			Ametys.cms.glossary.GlossaryDAO.editDefinition(params, this._validateCb, {scope: this} );
 		}
    },
    
    /**
     * Callback function called after creation or edition process
     */
    _validateCb: function (response, args)
    {
    	if (!response['error'])
    	{
    		this._box.close();
    		if (Ext.isFunction (this._cbFn))
        	{
        		this._cbFn (response.id);
        	}
    	}
    },
    
    /**
     * @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 {Object} config the configuration for the word definition dialog
 	 */
	_initForm: function (config)
 	{
 		var form = this._formPanel.getForm();
 		
 		if (this._mode === "new") 
        {
 			form.reset();
 			form.findField('word').setValue(config.word || '');
		    form.findField('themes').setLanguage(config.lang);
 			this._box.show();
        }
 		else
 		{
 			form.findField('id').setValue(config.id);
 			
 			Ametys.data.ServerComm.callMethod({
				role: "org.ametys.plugins.glossary.GlossaryDAO",
				methodName: 'getDefinition',
				parameters: [config.id],
				callback: {
					handler: this._setValues,
					scope: this
				},
				errorMessage: {
					category: this.self.getName(),
					msg: "{{i18n PLUGINS_GLOSSARY_GET_DEFINITION_ERROR}}"
				}
			});
 		}
 	},
 	
 	/**
 	 * Fill the form with some values.
 	 * @param {Object} data The definition.
 	 * @private
 	 */
 	_setValues: function(data)
 	{
 		var form = this._formPanel.getForm();
 		
	    form.findField('word').setValue(data.word);
	    form.findField('variants').setValue(data.variants.join(','));
	    form.findField('definition').setValue(data.content);
	    form.findField('displayOnText').setValue(data.displayOnText);
	    
	    var themes = data["themes"];
        var themeIds = [];
        for (var i = 0; i < themes.length; i++)
        {
           themeIds.push(themes[i].id);
        }
        form.findField('themes').setValue(themeIds);
	    
	    this._box.show();
 	},
 	
 	/**
 	 * 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,
                anchor: '90%',
                msgTarget: 'side'
            },
	        
	        border: false,
	        scrollable: true,
	        
	        items: [
		        {
		        	xtype: 'hidden',
		        	name: 'id'
		        },
		        {
		        	name: 'word',
		        	itemId: 'word',
		        	fieldLabel: "{{i18n PLUGINS_GLOSSARY_DEFINITION_DIALOG_WORD_LABEL}}",
	                ametysDescription: "{{i18n PLUGINS_GLOSSARY_DEFINITION_DIALOG_WORD_DESC}}",
	                allowBlank: false,
	                minLength: 2,
	                regexText: "{{i18n PLUGINS_GLOSSARY_DEFINITION_DIALOG_WORD_INVALID}}"
		        },
		        {
		        	name: 'variants',
	                fieldLabel: "{{i18n PLUGINS_GLOSSARY_DEFINITION_DIALOG_VARIANTS_LABEL}}",
	                ametysDescription: "{{i18n PLUGINS_GLOSSARY_DEFINITION_DIALOG_VARIANTS_DESC}}"
		        },
		        {
		        	xtype: 'textarea',
		        	name: 'definition',
	                fieldLabel: "{{i18n PLUGINS_GLOSSARY_DEFINITION_DIALOG_DEFINITION_LABEL}}",
	                ametysDescription: "{{i18n PLUGINS_GLOSSARY_DEFINITION_DIALOG_DEFINITION_DESC}}",
	                regexText: "{{i18n PLUGINS_GLOSSARY_DEFINITION_DIALOG_DEFINITION_INVALID}}",
	                allowBlank: false,
	                height: 140
		        },
		        {
                    xtype: 'edition.select-glossary-theme',
                    name: 'themes',
                    multiple: true,
                    fieldLabel: "{{i18n PLUGINS_GLOSSARY_DEFINITION_DIALOG_THEMES_LABEL}}",
                    ametysDescription: "{{i18n PLUGINS_GLOSSARY_DEFINITION_DIALOG_THEMES_DESC}}"
                },
		        {
		        	xtype: 'checkbox',
		        	name: 'displayOnText',
	                fieldLabel: "{{i18n PLUGINS_GLOSSARY_DEFINITION_DIALOG_DISPLAY_LABEL}}",
	                ametysDescription: "{{i18n PLUGINS_GLOSSARY_DEFINITION_DIALOG_DISPLAY_DESC}}",
	                inputValue: 'true',
	                checked: true
		        }
	        ]
        	
 		});
 		
 		return formPanel;
 	}
 	
 	
});