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

/**
 * A tree presenting the parameter files structure
 * @private
 */
Ext.define('Ametys.plugins.coreui.parameter.files.ParameterFilesTree', {
    extend: "Ametys.file.AbstractFileExplorerTree",
    
    allowFiltering : true,
    
    createTreeStore: function()
    {
        return Ext.create('Ext.data.TreeStore', {
            model: 'Ametys.file.AbstractFileExplorerTree.FileNode',
            proxy: {
                type: 'ametys',
                plugin: 'core-ui',
                url: 'params/files.json',
                reader: {
                    type: 'json',
                    rootProperty: 'nodes'
                }
            },
            folderSort: true,
            sorters: [{
                property: 'text',
                direction: 'ASC'
            }],
            root: {
                id: 'root',
                name: 'root',
                hasChild: true,
                editable: false,
                allowDrag: false,
                type: 'collection',
                iconCls: 'ametysicon-folder249',
                text: "{{i18n PLUGINS_CORE_UI_PARAMETERS_FILE_TOOL_ROOT_NODE}}",
                path: '',
                expanded: true,
                loaded: true // Prevent AJAX request
            }
        });
    },
    
    editNode: function(node, oldname, newname)
    {       
        Ametys.plugins.coreui.parameter.files.ParameterActions.rename(node.get('path'), newname, node.get('type'), Ext.bind(this._editNodeCb, this, [node, oldname], true));
    },
    
    /**
     * @private
     * Callback function called after renaming 
     * @param {String} path The path of renamed file
     * @param {String} name The name of the node
     * @param {Boolean} success True if the rename action succeed
     * @param {Ext.data.Model} node The edited node
     * @param {String} oldName The name before renaming
     */
    _editNodeCb: function(path, name, success, node, oldName)
    {
        if (!success)
        {
            this.updateNodeName(node, oldName);
        }
    },
    
    /**
     * Get the message target configuration for given node
     * @param {Ext.data.Model} node The node.
     * @param {Boolean} busMessage True if it is for a bus message, false if it is for the drag and drop.
     */
    getMessageTargetConfiguration: function(node, busMessage)
    {
        if (busMessage && node.isRoot())
        {
            return {
                id: Ametys.message.MessageTarget.PARAM_ROOT,
                parameters: {
                    path: node.get('path')
                }
            }
        }
        else if (node.get('type') == Ametys.file.AbstractFileExplorerTree.TYPE_RESOURCE)
        {
            return {
                id: Ametys.message.MessageTarget.PARAM_FILE,
                parameters: {
                    name: node.get('name'),
                    path: node.get('path')
                }   
            }
        }
        else
        {
            return {
                id: Ametys.message.MessageTarget.PARAM_FOLDER,
                parameters: {
                    name: node.get('name'),
                    path: node.get('path')
                }   
            }
        }
    },
        
    getMessageTargetIdForResource: function()
    {
        return Ametys.message.MessageTarget.PARAM_FILE;
    },
    
    getMessageTargetIdForCollection: function()
    {
        return function(target)
        {
            var targetId = target.getId();
            return targetId == Ametys.message.MessageTarget.PARAM_FOLDER || targetId == Ametys.message.MessageTarget.PARAM_ROOT;
        };
    },
    
    testTarget: function(target)
    {
        return target.getId() == Ametys.message.MessageTarget.PARAM_FILE || target.getId() == Ametys.message.MessageTarget.PARAM_FOLDER
    },
    
    _getFilteredPath: function(value, node, childNodesOnly, rootNode)
    {
        Ametys.data.ServerComm.callMethod({
            role: "org.ametys.core.ui.UIToolsFactoriesManager",
            id: "uitool-params-files",
            methodName: "getFilteredPath",
            parameters: [value, node.get('path')],
            callback: {
                scope: this,
                handler: this._getFilteredPathCb,
                arguments: {
                    node: node,
                    childNodesOnly: childNodesOnly,
                    rootNode: rootNode || node
                }
            },
            errorMessage: {
                category: this.self.getName(),
                msg: "{{i18n PLUGINS_CORE_UI_PARAMETERS_FILE_TOOL_FILTER_ERROR}}"
            },
            waitMessage: {
                target: this
            },
        });
    },
});