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

/**
 * Helper to open a dialog box to revert MCC state with comment
 * @private
 */
Ext.define('Ametys.plugins.odf.pilotage.helper.ODFTreeGridPanelHelper', {
    
    /**
     * @private
     * Method to save the edition of contents for some ODF tree grid panel.
     * The scope must be a grid panel 
     * @param {Object[]} contents The contents to save
     * @param {Function} callback The callback function to call at the end of the save operation.
     * @param {Object} additionalParams Additional parameters to pass to the server
    */
    _saveEditionWithContents: function(contents, callback, additionalParams)
    {
        // If the selection is located on a modified node with modified children it will lead to a wrong refresh due to our "random-id-xxxx"" that will change after reloading the same node
        // Removing the selection will avoid this
        // ODF-3792
        let selection = this.getSelection();
        let reselect = callback;
        if (selection.length > 0 && Object.keys(selection[0].getChanges()).length > 0 && selection[0].hasChildNodes())
        {
            let contentToReselect = selection[0].get('contentId');
            let me = this;
            const cb = callback;
            this.setSelection(this.getRootNode());
             
            reselect = function(success)
            {
                let rec = me.getStore().findRecord("contentId", contentToReselect, null, false, true, true);
                me.setSelection(rec);
                me.on('beforeselect', function() {
                    // we are acting soon, so the load will reselect the root node (that was selected a few lines above), that we want to avoid
                    return false; 
                }, me, {single: true});
                cb(success);
            }
            callback = reselect;
        }
        
        try
        {
            let me = this;
            
            // We are going to loop on all contents
            // But we want to call the callback only at the very end of theses asynchronous calls
            // So lets ignore the first n-1 calls.
            let barrierCallback = Ext.Function.createBarrier(contents.length, reselect);
            
            Ext.Array.forEach(contents, function(content) {
                let record = me._findRecords(content.getId())[0]; // we can take the first record since all records should display the same value
                
                let changes = record.getChanges();
                
                let params = [];
                params.push(me._getContentId(record));
                params.push(changes);
                
                if (additionalParams)
                {
                    params = params.concat(additionalParams);
                }
                
                Ametys.data.ServerComm.callMethod({
                    role: me.getInitialConfig('serverRole'),
                    methodName: "saveEdition",
                    parameters: params,
                    callback: {
                                scope: me,
                                handler: me._saveEditionCB,
                                arguments: {
                                    content: content,
                                    callback: barrierCallback
                                }
                            },
                    waitMessage: {
                        target: me,
                        msg: "{{i18n plugin.cms:CONTENT_EDITION_SAVING}}"
                    },
                    errorMessage: true
                });
        
                Ext.create("Ametys.message.Message", {
                    type: Ametys.message.Message.WORKFLOW_CHANGING,
                    
                    targets: {
                        id: me.messageTarget,
                        parameters: { contents: [content] }
                    }
                });
            });
        }
        catch (e)
        {
            Ametys.form.SaveHelper.SaveErrorDialog.showErrorDialog (null, e.message);
            callback(false);
            throw e;
        }
        
        if (contents && contents.length == 0)
        {
            // no content modified
            callback(true);
        }
    }
})