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

/**
 * Singleton class for the actions related to the extraction folders tool.
 * @private
 */
Ext.define('Ametys.plugins.extraction.ExtractionFoldersActions', {
    singleton: true,

    /**
     * Function called to add a new folder
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function
     */
    addFolder: function (controller)
    {
        var targets = controller.getMatchingTargets();
        
        if (targets.length > 0)
        {
            controller.serverCall(
                    'addFolder', [targets[0].getParameters().path, "{{i18n plugin.core-ui:PLUGINS_CORE_UI_PARAMETERS_FILE_ADD_FOLDER_NEW}}"], Ext.bind(this._addFolderCb,this),
                    {
                        errorMessage: { msg: "{{i18n plugin.core-ui:PLUGINS_CORE_UI_PARAMETERS_FILE_ADD_FOLDER_ERROR}}", category: Ext.getClassName(this) + '.addFolder'},
                        refreshing: true
                    }
            );
        }
    },
    
    /**
     * Callback invoked when adding a folder
     * @param {Object[]} response The JSON response from the server
     * @param {String} response.path the path of the folder
     * @param {String} response.parentPath the path of the parent 
     * @param {String} response.name the name of the folder
     */
    _addFolderCb : function(response) 
    {
        if (response.success)
        {
            var path = response['path'];
            var parentPath = response['parentPath'];
            var name = response['name'];
            
            Ext.create("Ametys.message.Message", {
                type: Ametys.message.Message.CREATED,
                parameters: {parentPath: parentPath},
                targets: {
                    id: Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FOLDER,
                    parameters: { 
                        path: path,
                        name: name,
                        canRead: true,
                        canRename: true,
                        canDelete: true,
                        canWrite: true,
                        canAssignRights: true
                    }
                }
            });
        }
    },
    
    /**
     * Function called to delete a folder
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function
     */
    removeFolder: function(controller)
    {
        var targets = controller.getMatchingTargets();
        
        if (targets.length > 0)
        {
            Ametys.Msg.confirm("{{i18n plugin.core-ui:PLUGINS_CORE_UI_PARAMETERS_FILE_DELETE_FOLDER_TITLE}}", 
                    "{{i18n plugin.core-ui:PLUGINS_CORE_UI_PARAMETERS_FILE_DELETE_FOLDER_CONFIRM}}", 
                    function(btn) {
                        this._doRemove(btn, targets[0], controller);
                    }, 
                    this);
        }
    },
    
    /**
     * @private
     * Internal callback for the #removeFolder function
     * @param {String} answer The id of the button pressed.
     * @param {Ametys.message.MessageTarget} target The target
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function     
     */
    _doRemove: function(answer, target, controller)
    {
        if (answer == 'yes')
        {
            var errorMsg = target.getId() == Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FOLDER ? "{{i18n plugin.core-ui:PLUGINS_CORE_UI_PARAMETERS_FILE_DELETE_FOLDER_ERROR}}" : "{{i18n plugin.core-ui:PLUGINS_CORE_UI_PARAMETERS_FILE_DELETE_FILE_ERROR}}";
            
            controller.serverCall(
                    'deleteFile', [target.getParameters().path], Ext.bind(this._doRemoveCb,this), {arguments: {target: target}},
                    {
                        errorMessage: { msg: errorMsg, category: Ext.getClassName(this) + '.removeFolder'},
                        refreshing: true
                    }
            );
        }
    },
    
    /**
     * Callback function after deletion.
     * @param {Object[]} result the server's response
     * @param {Object} params The callback arguments
     */
    _doRemoveCb: function(result, params)
    {
        if (result.success)
        {
            Ext.create("Ametys.message.Message", {
                type: Ametys.message.Message.DELETED,
                targets: params.target
            });
        }
    },
    
    /**
     * Function called to rename a folder
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function
     */
    renameFolder: function(controller)
    {
        var targets = controller.getMatchingTargets();
        
        if (targets.length > 0)
        {
            var name = targets[0].getParameters().name;
            
            Ametys.Msg.prompt(
                "{{i18n plugin.core-ui:PLUGINS_CORE_UI_PARAMETERS_FILE_RENAME_FOLDER_TITLE}}", 
                "{{i18n plugin.core-ui:PLUGINS_CORE_UI_PARAMETERS_FILE_RENAME_FOLDER_MSG}}", 
                function(btn, text) {
                    if (btn == 'ok' && text != name) 
                    {
                        this.rename(targets[0].getParameters().path, targets[0].getParameters().name, text, 'collection');
                    }
                },
                this, 
                false,
                name
            );
        }
    },

    /**
     * Rename a file or folder
     * @param {String} path The path of file to rename
     * @param {String} oldName The old name of file to rename
     * @param {String} newName The new name
     * @param {String} type The type of resource
     * @param {Function} [callback] Callback function. The function receives the following parameters:
     * @param {Boolean} callback.success true if the renaming was successful
     * @param {String} callback.path The path of the renamed file
     * @param {String} callback.name The name of the renamed file
     */
    rename: function(path, oldName, newName, type, callback)
    {
        var name = Ext.String.trim(newName);
        if (newName == '' || !/^[^\\/:*?"<>|]*$/.test(newName))
        {
            var alertMsg = type == 'resource' ? "{{i18n plugin.core-ui:PLUGINS_CORE_UI_PARAMETERS_FILE_RENAME_FILE_INVALID_CHARACTERS}}" : "{{i18n plugin.core-ui:PLUGINS_CORE_UI_PARAMETERS_FILE_RENAME_FOLDER_INVALID_CHARACTERS}}"
            Ametys.Msg.alert(
                "{{i18n plugin.core-ui:PLUGINS_CORE_UI_PARAMETERS_FILE_RENAME_FOLDER_FILE}}",
                alertMsg
            );
            
            if (Ext.isFunction(callback))
            {
                callback(false, path, newName);
            }
            return false;
        }
        
        Ext.create('Ametys.message.Message', {
            type: Ametys.message.Message.MODIFYING,
            targets: {
                id: Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FOLDER,
                parameters: {
                    path: path,
                    name: oldName
                }
            }
        });
        
        var errorMsg = type == 'resource' ? "{{i18n plugin.core-ui:PLUGINS_CORE_UI_PARAMETERS_FILE_RENAME_FILE_ERROR}}" : "{{i18n plugin.core-ui:PLUGINS_CORE_UI_PARAMETERS_FILE_RENAME_FOLDER_ERROR}}";

        Ametys.data.ServerComm.callMethod({
            role: 'org.ametys.core.ui.RibbonControlsManager',
            id: 'org.ametys.plugins.extraction.Folder.rename',
            methodName: 'renameFile',
            parameters: [path, newName],
            callback: {
                handler: this._renameCb,
                scope: this,
                arguments: {
                    name: newName, 
                    type: type, 
                    path: path,
                    callback: callback,
                    messageTargetType: type == 'resource' ? Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FILE : Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FOLDER
                }
            },
            errorMessage: {
                msg: errorMsg,
                category: this.self.getName()
            },
            waitMessage: true
         });
    },
    
    /**
     * @private
     * Callback invoked after renaming
     * @param {Object} result The server result
     * @param {Object} args the callback arguments
     */
    _renameCb: function(result, args)
    {
        if (result.error == 'already-exists')
        {
            var errorMsg = args.type == 'resource' ? "{{i18n plugin.core-ui:PLUGINS_CORE_UI_PARAMETERS_FILE_RENAME_FILE_ALREADY_EXISTS}}" : "{{i18n plugin.core-ui:PLUGINS_CORE_UI_PARAMETERS_FILE_RENAME_FOLDER_ALREADY_EXISTS}}";
            Ametys.Msg.show({
                title: "{{i18n plugin.core-ui:PLUGINS_CORE_UI_PARAMETERS_FILE_RENAME_FOLDER_FILE}}",
                msg: errorMsg,
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
            
            if (Ext.isFunction(args.callback))
            {
                args.callback(false, args.path, args.name);
            }
            return false;
        }
        
        Ext.create("Ametys.message.Message", {
            type: Ametys.message.Message.MODIFIED,
            
            targets: {
                id: args.messageTargetType,
                parameters: { 
                    path: result.path,
                    name: result.name
                }
            }
        });
        
        if (Ext.isFunction(args.callback))
        {
            args.callback(true, result.path, result.name);
        }
    }
});