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

/**
 * Tool to edit MCC in course 
 * @private
 */
Ext.define('Ametys.plugins.odf.pilotage.tool.ContentViewTreeGridTool', {
    extend: 'Ametys.plugins.odf.tree.AbstractODFTreeGridTool',

    /**
     * @config {String} searchModel The name of the search model to determin columns
     */

    constructor: function(config)
    {
        this.callParent(arguments);
        
        Ametys.data.ServerComm.callMethod({
            role: "org.ametys.cms.search.model.SearchModelHelper",
            methodName: "getColumnConfigurations",
            parameters: [this.searchModel, this.getContextualParameters()],
            callback: {
                handler: this._getColumnsCb,
                scope: this,
                arguments: arguments
            },
            errorMessage: {
                msg: "{{i18n plugin.cms:UITOOL_SEARCH_ERROR}}",
                category: Ext.getClassName(this)
            }
        });
    },
    
    _createTree: function()
    {
        return Ext.create('Ametys.plugins.odf.pilotage.tool.ContentViewTreeGridPanel', this._getTreeConfig());
    }, 
    
    _onWorkflowChanged: function(message)
    {
        // ignore
        // but default onWorkflowChanged call onModified that will be called twice on a real modification
    },
    
    /**
     * @private
     */
    getContextualParameters: function()
    {
        var params = Ametys.getAppParameters();

        // default language
        params.language = Ametys.cms.language.LanguageDAO.getCurrentLanguage();

        return params;
    },
    
    _wrapedRenderer(initialRenderer)
    {
        return function(value, metaData, record, rowIndex, colIndex, store, view) 
        {
            let headerCt = this.getHeaderContainer();
            let column = headerCt.getHeaderAtIndex(colIndex);
            
            metaData.tdCls += ' ftype-' + column.type;
            
            if (record.data.editionAvailable 
                && !(record.data['notEditableData'] === true)
                && !(record.data['notEditableDataIndex'] && Ext.Array.contains(record.data['notEditableDataIndex'], column.dataIndex))
                && !(record.data[column.dataIndex + '_external_status'] == 'external'))
            {
                metaData.tdCls += ' editable';
            }
            
            
            if (initialRenderer)
            {
                return initialRenderer.apply(this, arguments);
            }
            else
            {
                return value;
            }
        }
    },
    
    _getColumnsCb: function(columnsData, args)
    {
        let me = this;
        
        // apply fields for edition
        let fields = Ametys.plugins.cms.search.SearchGridHelper.getFieldsFromJson(columnsData);
        this._treePanel.store.model.replaceFields(fields, fields.map(f => f.name)); // Remove the given fields before replacing them
        this._treePanel.updateChangeListeners();

        // apply columns
        let columns = Ametys.plugins.cms.search.SearchGridHelper.getColumnsFromJson(columnsData, true, this._treePanel, false, null);
        columns.forEach(c => c.renderer = me._wrapedRenderer(c.renderer));
        columns.map(c => c.lockable = false);
        columns.map(c => c.sortable = false);
        columns.splice(0, 0, this._treePanel._getDefaultGridConfig()[0]); // Insert the hardcoded title xtreecolumn
        this._treePanel.reconfigure(this.store, columns, null, true);
    },
    
    _getTreeConfig: function()
    {
        var treeCfg = this.callParent(arguments);
        return Ext.apply(treeCfg, {
                activeIndicators: ["odf-indicator-code", "odf-indicator-shared-status", "odf-indicator-courselist-type", "odf-indicator-stepholder"],
                searchModel: this.searchModel,
                workflowEditActionId: this.getInitialConfig("workflowEditActionId")
        });
    },
    
    _setContentRootNode: function()
    {
        this._treePanel._showHideSaveBar(false);
        this.callParent(arguments);
    },
    
    close: function (manual)
    {
        if (this.isDirty())
        {
            Ametys.Msg.confirm("{{i18n plugin.cms:CONTENT_EDITION_UNSAVE_LABEL}}", 
                    "{{i18n plugin.cms:CONTENT_EDITION_UNSAVE_CONFIRM}}", 
                    function (answer) {
                        if (answer == 'yes')
                        {
                            this.setDirty(false);
                            this.close(manual);
                        }
                    },
                    this
            );
            return;
        }
        else
        {
            this.callParent (arguments);
        }
        
    },
    
    _refreshTree: function(message)
    {
        if (!this.isDirty()) // Do not refresh when dirty to avoid losing edited data
        {
            this.callParent(arguments);
        }
    }    
});