/*
 *  Copyright 2025 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 the list of right context where a selected profile is used
 */
Ext.define('Ametys.plugins.coreui.profiles.ProfilesUsesTool', {
    extend: 'Ametys.tool.Tool',
    
    createPanel: function()
    {
        this._profileSelector = Ext.create('Ametys.form.field.SelectProfile',{
            name: 'profile',
            itemId: 'profile',
            listeners: {
                change: {fn: this._onProfileSelection, scope: this}
            },
            includeReader: false,
            maxWidth: 300
        });
        
        this._contextStore = Ext.create("Ext.data.Store",{
            proxy: {
                type: 'ametys',
                plugin: 'core-ui',
                serverId: this.getServerId(),
                role: this.getServerRole(),
                methodName: 'getProfileUses',
                methodArguments: ['profileId'],
                reader : {
                    type : 'json',
                }
            },
            groupField: 'category',
            autoLoad: false,
            
            listeners: {
                'beforeload': {fn: this._onBeforeLoad, scope: this},
				'load': {fn: this._onLoad, scope: this}
            }
        });
        
        var contextList = Ext.create("Ext.grid.Panel", {
            itemId: 'context-list',

            // required because there is no header
            bodyBorder: false,
            
            store: this._contextStore,
            forceFit: true,
            columns: [{
                dataIndex: "label"
            }],
            
            features: [{
                    ftype:'grouping',
                    enableGroupingMenu: false,
                    groupHeaderTpl: '{name} ({children.length})',
            }],
            
            listeners: {
                selectionchange: {
                    fn: this._onContextSelection,
                    scope: this
                }
            }
        });
        
        this._leftPanel = Ext.create("Ext.panel.Panel", {
            layout: 'card',
            width: 300,
            split: true,
            dockedItems: this._getGridDockedItemsCfg(),
            items: [
                {
                    xtype: 'component',
                    cls: 'a-panel-text-empty',
                    itemId: 'no-profile',
                    html: "{{i18n PLUGINS_CORE_UI_TOOL_PROFILES_USES_NO_PROFILE_SELECTED}}"
                },
                {
                    xtype: 'component',
                    cls: 'a-panel-text-empty',
                    itemId: 'no-result',
                    html: "{{i18n PLUGINS_CORE_UI_TOOL_PROFILES_USES_NO_RESULT}}"
                },
                contextList
            ]
        });
        
        this._assignmentStore = Ext.create('Ametys.plugins.coreui.profiles.PermissionTargetStore', {
            proxy: {
                type: 'memory',
                reader: {
                    type: 'json',
                }
            }
        });
        
        var assignmentsGrid = Ext.create('Ametys.plugins.coreui.profiles.PermissionTargetGrid', {
            itemId: 'assignments-grid',
            store: this._assignmentStore,
            cls: 'a-grid-context-assignments',
            dockedItems: [{
                xtype: 'component',
                itemId: 'context-info',
                ui: 'tool-hintmessage'
            }],
                
            lockFirstColumn: false,
            enableColumnMove: false,
            enableColumnHide: false,
            sortableColumns: false,
            columns: [{
                dataIndex: 'result',
                flex:1,
                cellWrap:true,
                text: "{{i18n PLUGINS_CORE_UI_TOOL_PROFILES_EXPLANATION_COLUMN}}",
                renderer: v => Ametys.plugins.coreui.profiles.ProfilesGridHelper.computeExplanation(v.accessExplanations)
            }]
        });

        this._rightPanel = Ext.create("Ext.container.Container", {
            layout: 'card',
            flex: 1,
            split: true,
            items: [
                {
                    itemId: 'empty-card'
                },
                {
                    xtype: 'component',
                    cls: 'a-panel-text-empty',
                    itemId: 'no-context',
                    html: "{{i18n PLUGINS_CORE_UI_TOOL_PROFILES_USES_NO_CONTEXT_SELECTED}}"
                },
                assignmentsGrid
            ]
        });
        return Ext.create("Ext.panel.Panel", {
            layout: { 
                type: 'hbox',
                align: 'stretch'
            },
            cls: 'uitool-profile-uses',
            items: [this._leftPanel, this._rightPanel]
        });
    },
    
	setParams: function()
	{
		this.callParent(arguments);
		
		let profileTargets = Ametys.message.MessageBus.getCurrentSelectionMessage().getTargets(Ametys.message.MessageTarget.PROFILE);
        if (profileTargets.length > 0)
        {
			this._profileSelector.suspendEvent('change');
            this._profileSelector.setValue(profileTargets[0].getParameters().id)
        }
				
		this.refresh();
	},
	
	refresh: function()
	{
		this.showRefreshing();
		this._contextStore.load({
			callback: function() {
				this.showRefreshed();
				this._profileSelector.resumeEvent('change');
			}, 
			scope: this
		});
	},
	
    /**
     * @private
     */
    _getGridDockedItemsCfg: function()
    {
        return {
            dock: 'top',
            xtype: 'toolbar',
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            
            cls: 'toolbar',
            
            padding: '0 0 4px 5px',
            
            defaultType: 'textfield',
            items: [{
                    xtype: 'component',
                    html: "{{i18n PLUGINS_CORE_UI_TOOL_PROFILES_USES_PROFILE_SELECTION}}",
                    style: {
                        paddingTop: '5px',
                        paddingBottom: '5px'
                    }
                },
                this._profileSelector
            ]
        };
    },
    
    /**
     * @private
     */
    _onBeforeLoad: function(store, operation)
    {
		this._leftPanel.setLoading(true);
		
        var profileId = this._profileSelector.getValue();
		if (!profileId)
		{
			return false; // cancel load
		}
        operation.setParams(Ext.apply(operation.getParams() || {}, {
            profileId: profileId
        }));
    },
	
	/**
     * @private
     */
	_onLoad: function(store, records, successful, operation)
	{
		if (records && records.length > 0)
        {
            this._leftPanel.setActiveItem('context-list');
            this._rightPanel.setActiveItem('no-context')
        }
        else
        {
            this._leftPanel.setActiveItem('no-result');
            this._rightPanel.setActiveItem('empty-card');
        }
        this._leftPanel.setLoading(false);
	},
    
    /**
     * @private
     */
    _onProfileSelection: function(field, value)
    {
        if (value)
        {
            this._contextStore.load(); // reload used contexts
        }
        else
        {
            this._leftPanel.setActiveItem('no-profile');
        }
    },
    
    /**
     * @private
     */
    _onContextSelection: function(store, selected)
    {
        if (selected.length > 0)
        {
            this._assignmentStore.loadRawData(selected[0].get('permissions'));
            var grid = this._rightPanel.setActiveItem('assignments-grid');
            if (!grid)
            {
                grid = this._rightPanel.getLayout().getActiveItem();
            }
            var info = grid.getDockedComponent('context-info');
            
            // i18n params
            let profileLabel = this._profileSelector.getDisplayValue();
            let contextLabel = selected[0].get('label');
            info.setHtml(Ext.String.format("{{i18n PLUGINS_CORE_UI_TOOL_PROFILES_USES_PROFILE_SELECTION_HINT}}", profileLabel, contextLabel));
        }
        else
        {
            this._rightPanel.setActiveItem('no-context');
        }
    },
    
    getMBSelectionInteraction: function() 
    {
        return Ametys.tool.Tool.MB_TYPE_NOSELECTION;
    }
});