/*
 *  Copyright 2020 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 extraction definition files
 * @private
 */
Ext.define('Ametys.plugins.extraction.execution.ExtractionDefinitionsTree', {
    extend: "Ametys.file.AbstractFileExplorerTree",

    allowFiltering : true,
    
    createTreeStore: function()
    { 
        
        return Ext.create('Ext.data.TreeStore', {
            model: 'Ametys.plugins.extraction.execution.ExtractionFileNode',
            proxy: {
                type: 'ametys',
                plugin: 'extraction',
                url: 'definition/files.json',
                reader: {
                    type: 'json',
                    rootProperty: 'nodes'
                },
                extraParams: {
                    profile: this._profile
                }
            },
            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_EXTRACTION_DEFINITIONS_TREE_ROOT_NODE_DEFAULT_TEXT}}",
                path: '',
                expanded: true,
                loaded: true // Prevent AJAX request
            }
        });
    },

    /**
     * This event is thrown by the getDragData to add the 'source' of the drag.
     * @param {Object} item The default drag data that will be transmitted. You have to add a 'source' item in it: 
     * @param {Ametys.relation.RelationPoint} item.source The source (in the relation way) of the drag operation. 
     * @private
     */
    getDragInfo: function(item)
    {
        var targets = [];

        for (var i = 0; i < item.records.length; i++)
        {
            var record = item.records[i];
            if (record.get('canDelete'))
            {
                targets.push(this.getMessageTargetConfiguration(record, false));
            }
        }

        if (targets.length > 0)
        {
            item.source = {
                relationTypes: [Ametys.relation.Relation.MOVE],
                targets: targets
            };
        }
    },
    
    editNode: function(node, oldname, newname)
    {       
        Ametys.plugins.extraction.ExtractionFoldersActions.rename(node.get('path'), node.get('name'), 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.EXTRACTION_DEFINITION_ROOT,
                parameters: {
                    path: '',
                    name: 'root',
                    canRead: node.get('canRead'),
                    canRename: node.get('canRename'),
                    canDelete: node.get('canDelete'),
                    canWrite: node.get('canWrite'),
                    canAssignRights: node.get('canAssignRights')
                }
            }
        }
        else if (node.get('type') == Ametys.file.AbstractFileExplorerTree.TYPE_RESOURCE)
        {
            return {
                id: Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FILE,
                parameters: {
                    path: node.get('path'),
                    name: node.get('name'),
                    descriptionId: node.get('descriptionId'),
                    author: node.get('author'),
                    canRead: node.get('canRead'),
                    canWrite: node.get('canWrite'),
                    canDelete: node.get('canDelete'),
                    canAssignRights: node.get('canAssignRights')
                }   
            }
        }
        else
        {
            return {
                id: Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FOLDER,
                parameters: {
                    path: node.get('path'),
                    name: node.get('name'),
                    canRead: node.get('canRead'),
                    canRename: node.get('canRename'),
                    canDelete: node.get('canDelete'),
                    canWrite: node.get('canWrite'),
                    canAssignRights: node.get('canAssignRights')
                }   
            }
        }
    },

    /**
     * Refresh the whole tree
     * @param {Function} [callback] function to call after refreshing
     */
    initRootNodeParameter: function (callback)
    {
        if (this._isComputingRootNode)
        {
            return;
        }
        
        this._isComputingRootNode = true;

        Ametys.data.ServerComm.callMethod({
            role: "org.ametys.plugins.extraction.execution.ExtractionDAO",
            methodName: "getRootProperties",
            callback: {
                scope: this,
                handler: this._getRootNodeCb,
                arguments: {
                    callback: callback
                }
            },
            errorMessage: {
                category: this.self.getName(),
                msg: "{{i18n PLUGINS_EXTRACTION_TREE_ROOT_ERROR}}"
            },
            waitMessage: true
        });
    },
    
    /**
     * @private
     * Callback function after retrieving root node
     * @param {Object} response The server response
     * @param {Object} args the callback arguments
     */
    _getRootNodeCb: function (response, args)
    {
        this._isComputingRootNode = false;
        
        this.setRootNode({
            path: '',
            name: 'root',
            canWrite: response.canWrite,
            canRename: false,
            canDelete: false,
            canAssignRights: response.canAssignRights,
            type: "collection",
            expanded: true,
            text: "{{i18n PLUGINS_EXTRACTION_DEFINITIONS_TREE_ROOT_NODE_DEFAULT_TEXT}}"
        });

        if (Ext.isFunction (args.callback))
        {
            this.store.getRoot().on('expand', function() { args.callback (response.id); }, this, { single: true });
        }
    },
    
    getMessageTargetIdForResource: function(type)
    {
        return Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FILE;
    },
    
    getMessageTargetIdForCollection: function(type)
    {
        return Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FOLDER;
    },
    
    testTarget: function(target)
    {
        return target.getId() == Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FILE || target.getId() == Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FOLDER
    },
    
    _getFilteredPath: function(value, node, childNodesOnly, rootNode)
    {
        Ametys.data.ServerComm.callMethod({
            role: "org.ametys.plugins.extraction.execution.ExtractionDAO",
            methodName: "getFilteredPath",
            parameters: [node.get('path'), value],
            callback: {
                scope: this,
                handler: this._getFilteredPathCb,
                arguments: {
                    node: node,
                    childNodesOnly: childNodesOnly,
                    rootNode: rootNode || node
                }
            },
            waitMessage: {
                target: this
            },
            errorMessage: {
                category: this.self.getName(),
                msg: "{{i18n PLUGINS_EXTRACTION_EXTRACTIONS_LIST_TOOL_FILTER_ERROR}}"
            },
        });
    },

});