/*
 *  Copyright 2012 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.
 */

/**
 * Dialog box used to create or edit a QUERY.
 * @private
 */
Ext.define('Ametys.plugins.queriesdirectory.helper.CreateOrEditQuery', {
    singleton: true,
    
    /**
     * @property {Function} _cbFn The callback function to callback after creation
     * @private
     */
    
    /**
     * @property {Object} _params The parameters
     * @private
     */
    
    /**
     * @property {Boolean} _initialized True if the dialog box was already initialized
     * @private
     */
    _initialized: false,
    
    /**
     * Do the job (open the dialog box and so on)
     * @param {Object} config The configuration object:
     * @param {String} config.mode The mode: "new" to create a new query, "edit" to edit a query
     * @param {String} config.type The type of the query
     * @param {String} [config.title] The dialog box's title
     * @param {Object} [config.params] The query parameters. Can be null for creation.
     * @param {String} config.params.id The id of query to edit. Can not be null if mode is 'edit'.
     * @param {String} config.params.title The query title
     * @param {String} config.params.description The query description
     * @param {String} config.params.documentation The query documentation link
     * @param {Function} config.callback The callback on successful creation/modification of the query. The arguments are:
     * @param {Function} config.callback.id The query of the created or modified query
     */
    act: function (config)
    {
        this._mode = config.mode;
        this._type = config.type;
        this._cbFn = config.callback;
        this._params = config.params || {};

        if (!this._delayedInitialize())
        {
            return false;
        }
        
        this._box.setTitle(config.title || (this._mode == 'edit' ? "{{i18n PLUGINS_QUERIESDIRECTORY_EDIT_QUERY_DIALOG_CAPTION}}" : "{{i18n PLUGINS_QUERIESDIRECTORY_NEW_QUERY_DIALOG_CAPTION}}"));
        this._box.setIconCls('ametysicon-data110 ' + (this._mode == 'edit' ?  'decorator-ametysicon-edit45' : 'decorator-ametysicon-add64'));
        
        var parentDirectoryField = this._form.getComponent('parentDirectory');
        parentDirectoryField.setDisabled(this._mode == 'edit')
        parentDirectoryField.setHidden(this._mode == 'edit')
        
        this._box.show();
        this._initForm(this._params);
    },
    
    /**
     * @private
     * Initialize the dialog box.
     */
    _delayedInitialize: function ()
    {
        if (!this._initialized)
        {
            this._form = new Ext.FormPanel({
                border :false,
                bodyStyle :'padding:10px 10px 0',
                
                defaults: {
                    cls: 'ametys',
                    labelAlign: 'top',
                    labelSeparator: '',
                    width: '100%',
                    msgTarget: 'side'
                },
                
                items:[{
                            xtype: 'textfield',
                            fieldLabel :"* {{i18n PLUGINS_QUERIESDIRECTORY_NEW_QUERY_DIALOG_TITLE}}",
                            ametysDescription: this._type == "formatting" ? "{{i18n PLUGINS_QUERIESDIRECTORY_SAVE_AS_FORMATTING_DIALOG_TITLE_DESCRIPTION}}" : "{{i18n PLUGINS_QUERIESDIRECTORY_NEW_QUERY_DIALOG_TITLE_DESCRIPTION}}",
                            name: 'title',
                            itemId: 'title',
                            allowBlank: false               
                        }, 
                        {
                            xtype: 'textarea',
                            fieldLabel :"{{i18n PLUGINS_QUERIESDIRECTORY_NEW_QUERY_DIALOG_DESCRIPTION}}",
                            ametysDescription: this._type == "formatting" ? "{{i18n PLUGINS_QUERIESDIRECTORY_SAVE_AS_FORMATTING_DIALOG_DESCRIPTION_DESCRIPTION}}" : "{{i18n PLUGINS_QUERIESDIRECTORY_NEW_QUERY_DIALOG_DESCRIPTION_DESCRIPTION}}",
                            name :'description',
                            height: 180
                        },
                        {
                            xtype: 'textfield',
                            fieldLabel :"{{i18n PLUGINS_QUERIESDIRECTORY_NEW_QUERY_DIALOG_DOCUMENTATION}}", 
                            ametysDescription: this._type == "formatting" ? "{{i18n PLUGINS_QUERIESDIRECTORY_SAVE_AS_FORMATTING_DIALOG_DOCUMENTATION_DESCRIPTION}}" : "{{i18n PLUGINS_QUERIESDIRECTORY_NEW_QUERY_DIALOG_DOCUMENTATION_DESCRIPTION}}",
                            name :'documentation',
                            itemId: 'documentation',
                            warnRegex: new RegExp ('^https?://.*$'),
                            warnRegexText: "{{i18n plugin.core:PLUGINS_CORE_REGEXP_INVALID_HTTP_URL_START}}"
                        },
                        {
                            xtype: 'edition.query-container',
                            fieldLabel: "{{i18n PLUGINS_QUERIESDIRECTORY_NEW_QUERY_DIALOG_PATH}}",
                            name: 'parentDirectory',
                            itemId: 'parentDirectory',
                            allowBlank: true,
                            emptyText: "{{i18n PLUGINS_QUERIESDIRECTORY_NEW_QUERY_DIALOG_PATH_EMPTY}}"
                        }
                 ]
            });
                
            this._box = Ext.create('Ametys.window.DialogBox', {
                
                title: "{{i18n PLUGINS_QUERIESDIRECTORY_NEW_QUERY_DIALOG_CAPTION}}",
                iconCls : "ametysicon-basket decorator-ametysicon-data110",
                
                layout :'fit',
                maxWidth: 800,
                width: '80%',
                    
                items : [ this._form ],
                            
                defaultFocus: 'title',
                closeAction: 'hide',
                
                referenceHolder: true,
                defaultButton: 'validate',
                
                buttons : [{
                        reference: 'validate',
                        text :"{{i18n PLUGINS_QUERIESDIRECTORY_NEW_QUERY_DIALOG_OK}}",
                        handler : Ext.bind(this._ok, this)
                    }, {
                        text :"{{i18n PLUGINS_QUERIESDIRECTORY_NEW_QUERY_DIALOG_CANCEL}}",
                        handler : Ext.bind(this._cancel, this)
                    } 
                ]
            });
            
            this._initialized = true;
        }
        
        return this._initialized;
    },
    
    /**
     * @private
     * Initialize the box form
     * @param {Object} params The query parameters
     */
    _initForm: function (params)
    {
        var form = this._form.getForm(),
            titleField = form.findField('title'),
            descField = form.findField('description'),
            documentationField = form.findField('documentation'),
            parentDirectoryField = form.findField('parentDirectory');
        
        titleField.setValue(params.title || '');
        descField.setValue(params.description || '');
        documentationField.setValue(params.documentation || '');
        parentDirectoryField.setValue(null);
        
        titleField.clearInvalid();
        descField.clearInvalid();
        parentDirectoryField.clearInvalid();
        documentationField.clearWarning();
    },
    
    /**
     * The cancel button handler
     * @private
     */
    _cancel: function()
    {
        this._box.close();
    },
    
    /**
     * Callback on the ok button. 
     * @private
     */
    _ok: function()
    {
        var form = this._form.getForm();
        if (!form.isValid())
        {
            return;
        }
        
        if (this._mode == 'edit')
        {
            var params = [
                this._params.id, 
                form.findField('title').getValue(), 
                form.findField('description').getValue(),
                form.findField('documentation').getValue()
            ];
            
            Ametys.plugins.queriesdirectory.QueriesDAO.updateQuery(params, this._onCreated, {scope: this});
        }
        else
        {
            var params = [
                form.findField('title').getValue(), 
                form.findField('description').getValue(),
                form.findField('documentation').getValue(),
                this._type,
                this._params.content,
                form.findField('parentDirectory').getValue() || 'root'
            ];
            
            Ametys.plugins.queriesdirectory.QueriesDAO.createQuery(params, this._onCreated, {scope: this});
        }
    },
    
    /**
     * Callback of {@link #_ok} function
     * @param {Object} response The server response
     * @param {Array} params The server call parameters
     * @private
     */
    _onCreated: function(response, params)
    {
        if (response.id)
        {
            this._box.close();
            
            if (Ext.isFunction(this._cbFn))
            {
                this._cbFn(response);
            }
        }
    }
});