/*
 *  Copyright 2021 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.
 */
 
 /**
 * This tool displays all forms in READ access for current user
 * @private
 */
Ext.define('Ametys.plugins.forms.tool.FormDirectoriesTool', {
    extend: "Ametys.tool.Tool",
    
    constructor: function(config)
    {
        this.callParent(arguments);

        Ametys.message.MessageBus.on(Ametys.message.Message.DELETED, this._onDeletionMessage, this);
        Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onModifiedMessage, this);
        Ametys.message.MessageBus.on(Ametys.message.Message.CREATED, this._onModifiedMessage, this);
    },
    
    setParams: function (params)
    {
        this.callParent(arguments);
        this.showRefreshing();
        this._tree.initRootNodeParameter(Ext.bind(this._refreshCb, this));
    },
    
    refresh: function()
    {
        this.showRefreshing();
        this._tree.refresh(Ext.bind(this._refreshCb, this))
    },
    
    /**
     * @private
     * Callback function after (re)loading the tree
     */
    _refreshCb: function ()
    {
        this.showRefreshed();
        if (this._tree.getSelection().length == 0)
        {
            // Select root node
            this._tree.getSelectionModel().select(0);
        }
    },
    
    getMBSelectionInteraction: function() 
    {
        return Ametys.tool.Tool.MB_TYPE_ACTIVE;
    },

    onFocus: function()
    {
        this._previousSelection = Ametys.message.MessageBus.getCurrentSelectionMessage().getTargets();
        Ametys.plugins.forms.tool.FormDirectoriesTool.superclass.onFocus.call(this);
    },
    
    createPanel: function()
    {
        this._tree = Ext.create("Ametys.plugins.forms.tree.FormDirectoriesTree", { 
            rootVisible: true,
            alwaysShowEmptyDirectories: false, // when user has no right to handle directories, we want to hide empty directories
            stateful: true,         
            stateId: this.self.getName() + "$tree",     
            scrollable: true,
            allowEdition: true,
            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,
                      editor: {
                          xtype: 'textfield',
                          allowBlank: false,
                          selectOnFocus: true
                      }
                  },
                  {header: "{{i18n PLUGINS_FORMS_UITOOL_FORMS_COLUMN_AUTHOR}}", hidden: false, flex: 2, sortable: true, dataIndex: 'author', renderer: Ametys.grid.GridColumnHelper.renderUser},
                  {header: "{{i18n PLUGINS_FORMS_UITOOL_FORMS_COLUMN_PAGE_TITLE}}", flex: 2, sortable: true, multiple: true, dataIndex: 'pages', renderer: Ametys.plugins.forms.tree.FormDirectoriesTree.renderPage},
                  {header: "{{i18n PLUGINS_FORMS_UITOOL_FORMS_COLUMN_WORKFLOW}}", flex: 2, sortable: true, dataIndex: 'workflowLabel', align: 'center'},
                  {header: "{{i18n PLUGINS_FORMS_UITOOL_FORMS_COLUMN_ENTRIES}}", flex: 2, sortable: true, dataIndex: 'entriesAmount', align: 'center'},
                  {header: "{{i18n PLUGINS_FORMS_UITOOL_FORMS_COLUMN_LAST_SUBMISSION}}", flex: 2, sortable: true, dataIndex: 'lastEntry', renderer: Ametys.grid.GridColumnHelper.renderDateTime}
            ],
            
            listeners: {                
                selectionchange: this.sendCurrentSelection,
                itemdblclick: {
                    fn: function(view, record, item, index)
                    {
                        if (record.get('isForm') === true && record.get('canRead') === true)
                        {
                            Ametys.tool.ToolsManager.openTool("uitool-form", {id: record.getData().id, title: record.getData().title, path: record.getData().fullpath});
                            
                            var params = {
                                id: record.getData().id,
                                pageId: null,
                                questionId: null
                            };
                            
                            Ametys.tool.ToolsManager.openTool('uitool-form-preview', params);
                        }
                    }
                },
                scope: this
            }
        });
        return this._tree;
    },
    
    sendCurrentSelection: function()
    {
        var formTarget = [];
        var formDirectoryTarget = [];
        var selection = this._tree.getSelectionModel().getSelection();
        if(selection.length > 0){
            
            var currentRecord = selection[0]; //multiselection is not supported
            
            if(currentRecord.get('isForm'))
            {
                formTarget.push({
                    id: Ametys.message.MessageTarget.FORM_TARGET,
                    parameters: { 
                        id: currentRecord.getId(),
                        hasEntries: currentRecord.get('hasEntries'),
                        selection: this._previousSelection || null
                    }
                })
            }
            else
            {
                formDirectoryTarget.push({
                    id: Ametys.message.MessageTarget.FORM_DIRECTORY,
                    parameters: {
                        id: currentRecord.getId(),
                        name: currentRecord.get('text'),
                        canEditRight: currentRecord.get('canEditRight'),
                        canEdit: currentRecord.get('canEdit'),
                        canRename: currentRecord.get('canRename'),
                        canWrite: currentRecord.get('canWrite')
                    }
                })
            }
        }
        var targets = Ext.Array.merge(formTarget, formDirectoryTarget);
        
        Ext.create("Ametys.message.Message", {
            type: Ametys.message.Message.SELECTION_CHANGED,
            targets: targets
        });
    },
    
    _onModifiedMessage : function(message)
    {
        var targets = message.getTargets(function(target) {
            return target.getId() == Ametys.message.MessageTarget.FORM_TARGET || target.getId() == Ametys.message.MessageTarget.FORM_QUESTION || target.getId() == Ametys.message.MessageTarget.FORM_DIRECTORY || target.getId() == Ametys.message.MessageTarget.FORM_ENTRY
        });
        if (targets.length > 0 )
        {
            var id = targets[0].getParameters().formId || targets[0].getParameters().id;
            this._tree.reloadParent(id, true);
        }
    },
    
    /**
     * Listener on deletion messages
     * @param {Ametys.message.Message} message The deletion message.
     * @private
     */
    _onDeletionMessage: function (message)
    {
        var targets = message.getTargets(function(target) {
            return target.getId() == Ametys.message.MessageTarget.FORM_TARGET || target.getId() == Ametys.message.MessageTarget.FORM_QUESTION || target.getId() == Ametys.message.MessageTarget.FORM_DIRECTORY || target.getId() == Ametys.message.MessageTarget.FORM_ENTRY
        });
        if (targets.length == 1)
        {
            var id = targets[0].getParameters().formId || targets[0].getParameters().id;
            this._tree.reloadParent(id, false);
        }
        else if (targets.length > 1)
        {
            this.showOutOfDate();
        }
    }
});


/** Class defining target message names for forms and form directories */
Ext.define("Ametys.message.FormDirectoriesMessageTarget",
    {
        override: "Ametys.message.MessageTarget",
        
        statics: 
        {
            /**
             * @member Ametys.message.MessageTarget
             * @readonly
             * @property {String} FORM_DIRECTORY The target type is a form directory.  
             */
            FORM_DIRECTORY: "form-directory",
            
            /**
             * @member Ametys.message.MessageTarget
             * @readonly
             * @property {String} FORM The target type is a form. 
             */
            FORM_TARGET: "form-target"
        }
    }
);