/*
 *  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 renaming a new extraction.
 */
Ext.define('Ametys.plugins.extraction.edition.RenameExtractionAction', {
    singleton: true,
    
    /**
     * @private
     * @property {Ametys.window.DialogBox} _box The dialog box
     */
    /**
     * @private
     * @property {Ext.form.Panel} _form The form panel
     */
    /**
      * @private
      * @property {Boolean} _initialized True if the dialog box is initialized.
      */
    /**
     * @private
     * @property {Ametys.ribbon.element.ui.ButtonController} _controller The controller calling the extraction renaming
     */
    /**
     * @private
     * @property {String} _oldFilePath the extraction definition old file path
     */
    /**
     * @private
     * @property {String} _oldFileName the extraction definition old file name
     */
    /**
     * @private
     * @property {String} _descriptionId the extraction definition description
     */
    /**
     * @private
     * @property {Object} _author the extraction definition author
     * @property {String} _author.login the author's login
     * @property {String} _author.populationId the author's population identifier
     */
    /**
     * @private
     * @property {String} _canRead true if the current user can read the extraction definition
     */
    /**
     * @private
     * @property {String} _canWrite true if the current user can write the extraction definition
     */
    /**
     * @private
     * @property {String} _canAssignRights true if the current user can edit rights of the extraction definition
     */
    /**
     * @private
     * @property {String} _newFileName the extraction definition new file name
     */
    /**
     * @private
     * @property {String} _canAssignRights true if the current user can edit rights of the extraction definition
     */
    
    /**
     * Rename the selected extraction definition file
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the extraction renaming. This controller has to use org.ametys.plugins.extraction.edition.EditExtractionClientSideElement class
     */
    renameExtraction: function(controller)
    {
        this._controller = controller;
        var target = this._controller.getMatchingTargets()[0];
        this._oldFilePath = target.getParameters().path;
        this._oldFileName = target.getParameters().name;
        this._descriptionId = target.getParameters().descriptionId;
        this._author = target.getParameters().auhtor;
        this._canRead = target.getParameters().canRead;
        this._canWrite = target.getParameters().canWrite;
        this._canDelete = target.getParameters().canDelete;
        this._canAssignRights = target.getParameters().canAssignRights;
        this._openDialog();
    },
    
    /**
     * @private
     * Open the dialog to get extraction definition new file name
     */
    _openDialog: function()
    {
        if (!this._initialized)
        {
            this._form = this._createFormPanel();
            
            this._box = Ext.create('Ametys.window.DialogBox', {
                title: "{{i18n PLUGINS_EXTRACTION_RENAME_EXTRACTION_DIALOG_TITLE}}",
                iconCls: 'ametysicon-text70 decorator-ametysicon-add64',
                
                width: 400,
                scrollable: false,
                
                items: [this._form],
                
                closeAction: 'hide',
                
                referenceHolder: true,
                defaultButton: 'validate',
                defaultFocus: 'fileName', 
                selectDefaultFocus: true,
                
                buttons: [{
                    reference: 'validate',
                    text: "{{i18n PLUGINS_EXTRACTION_DIALOG_OK_BUTTON}}",
                    handler: Ext.bind(this._onOk, this)
                }, {
                    text: "{{i18n PLUGINS_EXTRACTION_DIALOG_CANCEL_BUTTON}}",
                    handler: Ext.bind(this._close, this)
                }]    
            });
            
            this._initialized = true;
        }
        
        this._initForm ();
    },
    
    /**
     * 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'
            },
            
            
            items: [
                {
                    name: 'fileName',
                    fieldLabel: "{{i18n PLUGINS_EXTRACTION_RENAME_EXTRACTION_FILE_NAME_INPUT_LABEL}}",
                    ametysDescription: "{{i18n PLUGINS_EXTRACTION_RENAME_EXTRACTION_FILE_NAME_INPUT_DESCRIPTION}}",
                    allowBlank: false,
                    validator: function(value) {
                        if (!/^[^\\/:*?"<>|]*$/.test(value))
                        {
                            return "{{i18n PLUGINS_EXTRACTION_EDIT_FILE_NAME_INVALID_CHARACTERS_ERROR}}";
                        }
                        
                        if (!Ext.String.endsWith(value, ".xml", true))
                        {
                            return "{{i18n PLUGINS_EXTRACTION_EDIT_FILE_NAME_INVALID_EXTENSION_ERROR}}";
                        }
                        
                        return true;
                    }
                }
            ]
            
        });
        
        return formPanel;
    },
    
    /**
     * @private
     * Initializes the form.
     */
    _initForm: function()
    {
        var form = this._form.getForm();
        form.reset();
        
        form.findField('fileName').setValue(this._oldFileName);
        form.findField('fileName').clearInvalid();
        
        this._box.show();
    },
    
    /**
    * @private
    * Handler for the 'ok' button of the dialog box
    */
    _onOk: function()
    {
        var form = this._form.getForm();
        if (!form.isValid())
        {
            return;
        }
        
        Ext.create('Ametys.message.Message', {
            type: Ametys.message.Message.MODIFYING,
            targets: {
                id: Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FILE,
                parameters: {
                    path: this._oldFilePath,
                    name: this._oldFileName,
                    descriptionId: this._descriptionId,
                    author: this._author,
                    canRead: this._canRead,
                    canWrite: this._canWrite,
                    canDelete: this._canDelete,
                    canAssignRights: this._canAssignRights
                }
            }
        });
        
        this._box.mask();
        var fileName = form.getValues().fileName;
        this._controller.serverCall('renameExtraction', [this._oldFilePath, fileName], Ext.bind(this._renameExtractionCb, this), { ignoreCallbackOnError: false });
    },
    
    /**
     * @private
     * Callback called when the extraction has been renamed
     * @param {Object} response response from server.
     */
    _renameExtractionCb: function(response)
    {
        this._box.unmask();
        if (response.success)
        {
            Ext.create('Ametys.message.Message', {
                type: Ametys.message.Message.MODIFIED,
                targets: {
                    id: Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FILE,
                    parameters: {
                        path: response.path,
                        name: response.name,
                        descriptionId: this._descriptionId,
                        author: this._author,
                        canRead: this._canRead,
                        canWrite: this._canWrite,
                        canDelete: this._canDelete,
                        canAssignRights: this._canAssignRights
                    }
                }
            });
            
            this._close();
        }
        else
        {
            Ametys.Msg.show({
                title: "{{i18n PLUGINS_EXTRACTION_RENAME_EXTRACTION_ERROR_DIALOG_TITLE}}",
                msg: response.error == 'already-exists' ? "{{i18n PLUGINS_EXTRACTION_ERROR_FILE_ALREADY_EXISTS_DIALOG_MSG}}" : "{{i18n PLUGINS_EXTRACTION_RENAME_EXTRACTION_ERROR_DIALOG_MSG}}",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
            });
        }
    },
    
    /**
     * @private
     * Callback for the "cancel" button of the dialog. Close the dialog.
     */
    _close: function()
    {
        this._box.close();
    }
});