/*
 *  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 a new extraction.
 */
Ext.define('Ametys.plugins.extraction.edition.CreateExtractionAction', {
    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} _parentPath The path of the folder parent of the definition file to create. Can be empty if the file is created at the root of definitions
     */
    
    /**
     * Creates a new 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
     */
    createExtraction: function(controller)
    {
        this._controller = controller;
        var target = this._controller.getMatchingTargets()[0];
        
        this._parentPath = "";
        if (target.getId() == Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FOLDER)
        {
            this._parentPath = target.getParameters().path + "/";
        }
        
        this._openDialog();
    },
    
    /**
     * @private
     * Open the dialog to create an extraction
     */
    _openDialog: function()
    {
        if (!this._initialized)
        {
            this._form = this._createFormPanel();
            
            this._box = Ext.create('Ametys.window.DialogBox', {
                title: "{{i18n PLUGINS_EXTRACTION_CREATE_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: [
                {
                    itemId: 'fileName',
                    name: 'fileName',
                    fieldLabel: "{{i18n PLUGINS_EXTRACTION_CREATE_EXTRACTION_FILE_NAME_INPUT_LABEL}}",
                    ametysDescription: "{{i18n PLUGINS_EXTRACTION_CREATE_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('');
        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;
        }
        
        if (Ext.isFunction(this._callback))
        {
            this._callback(form.getValues());
        }
        
        this._box.mask();
        var formValues = form.getValues();
        var definitionFilePath = this._parentPath + formValues.fileName;
        var language = Ametys.cms.language.LanguageDAO.getCurrentLanguage();
        this._controller.serverCall('createExtraction', [definitionFilePath, language], Ext.bind(this._createExtractionCb, this), { ignoreCallbackOnError: false });
    },
    
    /**
     * @private
     * Callback on extraction creation
     * @param {Object} response response from server.
     */
    _createExtractionCb: function(response)
    {
        this._box.unmask();
        if (response.success)
        {
            // open details tool
            Ametys.tool.ToolsManager.openTool('uitool-extraction-details', {
                id: response.path,
                name: response.name,
                descriptionId: response.descriptionId,
                author: response.author,
                canRead: response.canRead,
                canWrite: response.canWrite,
                canDelete: response.canDelete,
                canAssignRights: response.canAssignRightss
            });
            
            Ext.create('Ametys.message.Message', {
                type: Ametys.message.Message.CREATED,
                targets: {
                    id: Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FILE,
                    parameters: {
                        path: response.path,
                        name: response.name,
                        descriptionId: response.descriptionId,
                        author: response.author,
                        canRead: response.canRead,
                        canWrite: response.canWrite,
                        canDelete: response.canDelete,
                        canAssignRights: response.canAssignRights
                    }
                }
            });
            
            this._close();
        }
        else
        {
            Ametys.Msg.show({
                title: "{{i18n PLUGINS_EXTRACTION_CREATE_EXTRACTION_ERROR_DIALOG_TITLE}}",
                msg: response.error == 'already-exists' ? "{{i18n PLUGINS_EXTRACTION_ERROR_FILE_ALREADY_EXISTS_DIALOG_MSG}}" : "{{i18n PLUGINS_EXTRACTION_CREATE_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();
    }
});