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

/**
 * Forms directory context for profile assignments.
 */
Ext.define('Ametys.plugins.forms.FormsDirectoryRightAssignmentContext', {
    extend: 'Ametys.plugins.coreui.profiles.AbstractRightAssignmentContext',

    getComponent: function()
    {
        this._grid = Ext.create('Ametys.plugins.forms.tree.FormDirectoriesTree', {
            rootVisible: true,
            alwaysShowEmptyDirectories: true, // when user has no right to handle directories, we want to hide empty directories
            stateful: true,         
            stateId: this.self.getName() + "$tree",     
            scrollable: true,
            profile: 'right_access',

            cls: 'uitool-form-directories',
            columns: [
                  {
                      xtype: 'treecolumn', 
                      header: "{{i18n PLUGINS_FORMS_UITOOL_FORMS_COLUMN_TITLE}}", 
                      flex: 3, 
                      sortable: true, 
                      dataIndex: 'text', 
                      renderer: Ametys.plugins.forms.tree.FormDirectoriesTree.renderTitle
                  },
                  {
                	  header: "{{i18n PLUGINS_FORMS_UITOOL_FORMS_COLUMN_AUTHOR}}",
					  hidden: false,
					  flex: 2,
					  sortable: true,
					  dataIndex: 'author',
					  renderer: Ametys.grid.GridColumnHelper.renderUser
				  },
              ]
        });
        this._grid.on('selectionchange', this._onSelectionChanged, this);
        return this._grid;
    },
    
    initialize: function()
    {
        var me = this;
        this._grid.initRootNodeParameter(function(){
            if (me._formsDirectoryPathToSelect)
            {
                me._grid.selectPath(me._grid.getRootNode().get('text') + ' > ' + me._formsDirectoryPathToSelect, "text", " > ")
            }
            else
            {
                // Select root node
                me._grid.getSelectionModel().deselectAll();
                me._grid.getSelectionModel().select(0);
            }
        });
        
        Ametys.message.MessageBus.on(Ametys.message.Message.DELETED, this._onModifiedOrDeletionMessage, this);
        Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onModifiedOrDeletionMessage, this);
    },
    
    dispose: function()
    {
        // Unregister the tool for all messages 
        Ametys.message.MessageBus.unAll(this);
    },
    
    isSupported: function (message)
    {
        return message.getTargets(Ametys.message.MessageTarget.FORM_TARGET).length > 0 || message.getTargets(Ametys.message.MessageTarget.FORM_DIRECTORY).length > 0;
    },
    
    initContext: function (message)
    {
        var formTarget = message.getTarget();
        if (formTarget != null)
        {
            this._formsDirectoryPathToSelect = formTarget.getParameters().fullPath;
        }
    },
    
    /**
     * @private
     * Listener when the selection in the grid has changed
     * @param {Ext.selection.Model} model The selection model
     * @param {Ext.data.Model[]} selected The selected records
     */
    _onSelectionChanged: function(model, selected)
    {
        if (selected.length > 0)
        {
            var object = selected[0];
            var data = object.data;
            if (data.canEditRight)
            {
                var hintTextContext;
                if (!data.root)
                {
                    hintTextContext = (data.isForm ? "{{i18n PLUGINS_FORMS_FORMSDIRECTORYACCESS_CONTEXT_HINT_FORM}}" : "{{i18n PLUGINS_FORMS_FORMSDIRECTORYACCESS_CONTEXT_HINT_FORMDIRECTORY}}") + " <b>" + Ext.String.escapeHtml(selected[0].get('title')) + "</b>";
                }
                else
                {
                    hintTextContext ="{{i18n PLUGINS_FORMS_FORMSDIRECTORYACCESS_CONTEXT_HINT_ROOT}}";
                }
                
                this._changeObjectContext(object.get('id'), hintTextContext, false);
            }
            else
            {
                this._changeObjectContext(null);
            }
            
        }
        else
        {
            this._changeObjectContext(null);
        }
    },
	
    /**
     * Listener on modified or deletion messages
     * @param {Ametys.message.Message} message The deletion message.
     * @private
     */
    _onModifiedOrDeletionMessage: function (message)
    {
        var targets = message.getTargets(function(target) {
            return target.getId() == Ametys.message.MessageTarget.FORM_TARGET || target.getId() == Ametys.message.MessageTarget.FORM_DIRECTORY;
        });
        
        if (targets.length == 1)
        {
            var id = targets[0].getParameters().id || targets[0].getParameters().formId;
            this._grid.reloadParent(id, false);
        }
        else if (targets.length > 1)
        {
            this.showOutOfDate();
        }            
    }
});