/*
 *  Copyright 2018 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.
 */
 
/**
 * @private
 * This tool displays a ldap node
 */ 
Ext.define('Ametys.plugins.datasourcesexplorer.tool.DatasourcesExplorerLDAPNodeViewTool', {
    extend: 'Ametys.tool.Tool',
    
    /**
     * @private
     * @property {String} _datasourceId The displayed datasource id
     */
    /**
     * @private
     * @property {String} _ldapDN The ldap dn
     */
    /**
     * @private
     * @property {String} _fullLDAPDN The ldap dn with the '#' fake node to split results
     */
    /**
     * @private
     * @property {Ext.grid.Panel} _grid The main grid panel
     */

    constructor: function(config)
    {
        this.callParent(arguments);
        
        // Bus messages listeners
        Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onModified, this);
        Ametys.message.MessageBus.on(Ametys.message.Message.DELETED, this._onDeleted, this);
    },

    createPanel: function()
    {
        var store = this.createStore();
        
        this._grid = Ext.create('Ext.grid.Panel', {
            store: store,
            columns: [
                { text: 'Name', dataIndex: 'name', flex: 1 },
                { text: 'Value', dataIndex: 'value', flex: 1 }
            ]
        });
        
        return this._grid;
    },
    
        /**
     * @protected
     * Get the store the grid should use as its data source.
     * @return {Ext.data.Store} The store
     */
    createStore: function()
    {
        
        
        return Ext.create('Ext.data.Store', {
            model: 'Ametys.plugins.datasourcesexplorer.tool.ldap.Node',
            autoDestroy: true,
            
            proxy: {
                type: 'ametys',
                plugin: 'datasources-explorer',
                role: 'org.ametys.plugins.datasourcesexplorer.GetLDAPData',
                methodName: 'getData',
                methodArguments: [ 'datasourceId', 'dn' ],
                reader: {
                    type: 'json',
                    rootProperty: 'data'
                }
            },
             
            sorters: [
                {
                    property: 'name',
                    direction: 'ASC'
                }
            ],
            
            listeners: {
                'beforeload': {fn: this._onBeforeLoad, scope: this}
            }

        });
    },

    /**
     * Function called before loading the store
     * @param {Ext.data.Store} store The store
     * @param {Ext.data.operation.Operation} operation The object that will be passed to the Proxy to load the store
     * @private
     */
    _onBeforeLoad: function(store, operation)
    {
        if (this._ldapDN)
        {
            this._grid.getView().unmask();

            operation.setParams( Ext.apply(operation.getParams() || {}, {
                datasourceId: this._datasourceId,
                dn: this._ldapDN
            }));
        }
        else
        {
            // not parametrized yet
            return false;
        }
    },
    
    setParams: function(params)
    {
        this.callParent(arguments);
        this._datasourceId = params['datasource-id'];
        this._ldapDN = params['dn'].replace(/(,#[^,]*)/g, '');
        this._fullLDAPDN = params['dn'];
        this.setTitle(this._ldapDN.replace(/,/g, ', '));
        this.refresh();
    },
    
    getMBSelectionInteraction: function() 
    {
        return Ametys.tool.Tool.MB_TYPE_ACTIVE;
    },
    
    sendCurrentSelection : function()
    {
        var targets = [];
        targets.push({
            id: Ametys.message.MessageTarget.DATASOURCE_LDAPNODE,
            parameters: {
                id: this._datasourceId,
                dn: this._fullLDAPDN
            }
        });
        
        Ext.create("Ametys.message.Message", {
            type: Ametys.message.Message.SELECTION_CHANGED,
            targets: targets
        });
    },
    
    refresh: function ()
    {
        this.showRefreshing();
        this._grid.getStore().load({callback: this.showRefreshed, scope: this});
    },

    /**
     * @private
     * Handler function invoked whenever a {@link Ametys.message.Message#MODIFIED} message is sent out on the 
     * message bus. Update the corresponding record of the grid panel's store.
     * @param {Ametys.message.Message} message the message
     */
    _onModified: function (message)
    {
        var targets = message.getTargets(Ametys.message.MessageTarget.DATASOURCE);
        for (var i=0; i < targets.length; i++)
        {
            if (target.getParameters().id == this._datasourceId)
            {
                this.showOutOfDate();
                break;
            }
        }
    },
    
    /**
     * @private
     * Handler function invoked whenever a {@link Ametys.message.Message#DELETED} message 
     * is sent out on the message bus. Delete the corresponding record from the grid panel's store.
     * @param {Ametys.message.Message} message the message
     */
    _onDeleted: function (message)
    {
        var targets = message.getTargets(Ametys.message.MessageTarget.DATASOURCE);
        for (var i=0; i < targets.length; i++)
        {
            if (target.getParameters().id == this._datasourceId)
            {
                this.close();
                break;
            }
        }
    }
});