/*

 *  Copyright 2018 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.
 */
/**
 * The dialogBox to create or edit a microthesaurus
 * @private
 */
Ext.define('Ametys.plugins.thesaurus.helper.EditMicrothesaurusDialogBox', {
	singleton: true,
	
    /**
     * Configure and open the dialog box
     * @param {Object} config The configuration options :
     * @param {Object} [config.mode=new] The mode : 'new' for creation, 'edit' for edition
     * @param {Object} [config.thesaurusId] The id of default thesaurus to select
     * @param {Object} [config.label] The label of microthesaurus to edit. Required if mode equals 'edit'
     * @param {Object} [config.microthesaurusId] The id of microthesaurus to edit. Required if mode equals 'edit'
     * @param {Function} config.callback The callback function invoked after creation of microthesaurys. The callback function will received the following parameters:
     * @param {Object} config.callback.contentTypeInfos All information about the created content type 
     */
    open: function(config)
    {
        this._mode = config.mode || 'new';
        this._createDialogBox();
        this._thesaurusId = config.thesaurusId;
        
        this._initForm(config);
        this._box.show();
    },
    
    /**
     * @private
     * Initialize the form
     * @param {Object} config The configuration object
     */
    _initForm: function (config)
    {
        if (this._mode == 'new')
        {
            this._box.down("textfield[itemId='microthesaurus-id']").setValue("");
            this._box.down("textfield[itemId='microthesaurus-label']").setValue("");
        }
        else
        {
            this._initialLabel = config.label;
            this._box.down("textfield[itemId='microthesaurus-id']").setValue(config.microthesaurusId);
            this._box.down("textfield[itemId='microthesaurus-label']").setValue(config.label);
        }
    },
    
    /**
     * @private
     * Create the dialog to add or edit a content type
     */
    _createDialogBox: function()
    {
        this._form = this._createFormPanel();
        
        this._box = Ext.create('Ametys.window.DialogBox', {
            title: this._mode == 'new' ? "{{i18n PLUGINS_THESAURUS_NEW_MICROTHESAURUS_DIALOG_CAPTION}}" : "{{i18n PLUGINS_THESAURUS_EDIT_MICROTHESAURUS_DIALOG_CAPTION}}",
            width: 400,
            layout: 'fit',
            scrollable: true,
            iconCls: "ametysicon-reading " + (this._mode == 'new' ? "decorator-ametysicon-add64" : "decorator-ametysicon-edit45"),
            referenceHolder: true,
            
            items: [this._form],
            
            closeAction: 'destroy',
            buttons :
                [{
                    xtype: 'button',
                    text: '{{i18n PLUGINS_THESAURUS_CREATE_MICROTHESAURUS_VALIDATE}}',
                    handler: this._validate,
                    scope: this
                },
                {
                    xtype: 'button',
                    text: '{{i18n PLUGINS_THESAURUS_CREATE_MICROTHESAURUS_CANCEL}}',
                    handler: this._cancel,
                    scope: this
                }]
        });
    },
    
    /**
     * Create the form to edit the microthesaurus
     * @return {Ext.form.Panel} The form
     */
    _createFormPanel: function()
    {
    	this._thesaurusStore = Ext.create('Ext.data.Store', {
			model: 'Ametys.plugins.thesaurus.helper.EditMicrothesaurusDialogBox.ThesaurusEntry',
			sortOnLoad: true,
			sorters: [{property: 'label', direction:'ASC'}],
			proxy: {
				type: 'ametys',
				plugin: 'thesaurus',
				url: 'thesaurus.json',
				reader: {
					type: 'json',
					rootProperty: 'thesaurii'
				}
			},
			autoLoad: true,
          	listeners: {
          		'load':{fn: this._onLoad, scope : this, single: true}
			}
		});
        
    	var regex = new RegExp("^[\\w-.]*$");
    	var formPanel = Ext.create('Ext.form.Panel', {
    		labelWidth: 80,
    		defaults:{
    			labelAlign: 'right',
        		labelSeparator: '',
        		width: '100%',
        		msgTarget: 'side'
    		},
    		layout: 'anchor',
	        items: [{
	            xtype: 'combobox',
	            fieldLabel: '{{i18n PLUGINS_THESAURUS_CREATE_MICROTHESAURUS_THESAURUS_LABEL}}',
	            ametysDescription: '{{i18n PLUGINS_THESAURUS_CREATE_MICROTHESAURUS_THESAURUS_DESC}}',
	            itemId: "parent-thesaurus",
	            name: 'thesaurus',
	            allowBlank: false,
	            editable: false,
	            readOnly: this._mode == 'new' ? false : true,
	    	    disabled: this._mode == 'new' ? false : true,
	            displayField: 'label',
	            store: this._thesaurusStore,
	            valueField: 'id'
	        }, {
	            xtype: 'textfield',
	            allowBlank: false,
	            name: 'label',
	            fieldLabel: '{{i18n PLUGINS_THESAURUS_CREATE_MICROTHESAURUS_MICROTHESAURUS_TITLE_LABEL}}',
	            ametysDescription: '{{i18n PLUGINS_THESAURUS_CREATE_MICROTHESAURUS_MICROTHESAURUS_TITLE_DESC}}',
	            itemId: "microthesaurus-label",
	            enableKeyEvents: true,
	            listeners: {
	            	'keyup':{
	            		fn: this._onKeyUp, scope: this
	            	}
	            }
	        },
	        {
	            xtype: 'textfield',
	            allowBlank: false,
	            name: 'id',
	            fieldLabel: '{{i18n PLUGINS_THESAURUS_CREATE_MICROTHESAURUS_MICROTHESAURUS_NAME_LABEL}}',
	            ametysDescription: '{{i18n PLUGINS_THESAURUS_CREATE_MICROTHESAURUS_MICROTHESAURUS_NAME_DESC}}',
	            itemId: "microthesaurus-id",
	            regex: regex,
	            regexText: "{{i18n PLUGINS_THESAURUS_MICROTHESAURUS_ID_INCORRECT_ERROR_MESSAGE}}",
	            hidden: this._mode == 'new' ? false : true
	        }
	        ]
		});
   	
		return formPanel; 
    },
    
    /**
	 * @private Function called when the form is validated
	 */
	_validate : function() 
    {
		if (!this._form.getForm().isValid()) 
        {
			return;
		}

		var values = this._form.getForm().getValues();

		if (this._mode == 'edit' && values.label == this._initialLabel) 
        {
			// No change
			this._box.close();
			return;
		}

		Ametys.Msg.confirm("{{i18n PLUGINS_THESAURUS_RESTART_LABEL}}",
				"{{i18n PLUGINS_THESAURUS_RESTART_CONFIRM}}", 
                function(answer) {
					if (answer == 'yes') {
						if (this._mode == 'new') 
                        {
							Ametys.plugins.thesaurus.ThesaurusDAO.createMicrothesaurus([values.label, values.thesaurus, values.id], this._createMicrothesaurusCb, {scope : this});
						} 
                        else 
                        {
							Ametys.plugins.thesaurus.ThesaurusDAO.updateMicrothesaurus([values.id, values.label]);
						}
					}
				}, this);
	},
   
    /**
     * Callback function invoked after creation of microthesaurus
     * @param {Object} result teh server result
     * @private
     */
    _createMicrothesaurusCb: function(result)
    {
        if (!result.success && result.alreadyExist)
        {
            Ametys.Msg.show({
                title: "{{i18n PLUGINS_THESAURUS_NEW_MICROTHESAURUS_DIALOG_CAPTION}}",
                msg: "{{i18n PLUGINS_THESAURUS_DAO_CREATE_MICROTHESAURUS_ALREADY_EXISTS_ERROR}}",
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
            
            this._box.down("textfield[itemId='microthesaurus-id']").setValue(result.suggestedName);
        }
        else
        {
            this._box.close();
        }
    },
   
    /**
      * @private
      * Function called when the form is canceled
      */
    _cancel: function()
    {
	   this._box.close();
    },
   
   /**
    * @private
    * Listener called when a key is pressed in the microthesaurus name label
    */
    _onKeyUp: function()
    {
    	if (this._mode == 'new')
    	{
    		var microthesaurusLabel = this._box.down("textfield[itemId='microthesaurus-label']").getValue();
        	this._box.down("textfield[itemId='microthesaurus-id']").setValue(microthesaurusLabel.normalize('NFD').replace(/[^a-zA-Z0-9-_.]/g, ""));
    	}
    },
    
    /**
     * @private
     * Listener called when the thesaurus store is loaded. Set the value to the thesaurus created if it's the case.
     */
    _onLoad: function()
    {
    	if (this._thesaurusId != "undefined")
    	{
    		this._box.down("combobox[itemId='parent-thesaurus']").setValue(this._thesaurusId);
    	}
    }
});

Ext.define('Ametys.plugins.thesaurus.helper.EditMicrothesaurusDialogBox.ThesaurusEntry', { 
    extend: 'Ext.data.Model',
    
    fields: [
             {name: 'name', type: 'string'}
         ]
});