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

 /**
  * MCC course tree grid panel
  * @private
  */
Ext.define('Ametys.plugins.odf.pilotage.tool.MCCCourseTreeGridPanel', {
    extend: 'Ametys.plugins.odf.pilotage.tool.ContentViewTreeGridPanel',
    
    constructor: function(config)
    {
        config.cls = Ext.Array.from(config.cls);
        config.cls.push("mcccoursetreegrid");
		
        this.callParent(arguments);
    },
	
	// Override to get available actions from server call
	_beforeEditContentCB: function(content, record)
    {
        if (content == null)
        {   
            Ametys.cms.content.EditContentsView.prototype._beforeEditContentCB.apply(this, [content, record]);        }
        else 
        {
			if (content.getAvailableActions().indexOf(this.workflowEditActionId) != -1)
			{
				Ametys.cms.content.EditContentsView.prototype._beforeEditContentCB.apply(this, [content, record]);
			}
			else
			{
				// Test if edit workflow action id is available for current path
				Ametys.data.ServerComm.callMethod({
					role: this.getInitialConfig('serverRole'),
					methodName: "canEditRepeaterWithPath",
					parameters: [
						content.getId(),
						record.get("educationalPaths")[0].path.split(";")
					],
					callback: {
						handler: this._canEditRepeaterWithPathCB,
						scope: this,
						arguments: {
							content: content,
							record: record
						}
					},
		            errorMessage: true,
					waitMessage: false
				});
			}
        }
    },
	
	_canEditRepeaterWithPathCB: function (available, args)
	{
		// Add edit workflow action id to available actions
		let availableActions = args.content.getAvailableActions();
		if (available)
		{
			availableActions.push(this.workflowEditActionId);	
		}
		args.content._availableActions = availableActions;
		
		Ametys.cms.content.EditContentsView.prototype._beforeEditContentCB.apply(this, [args.content, args.record]);
	},
	
    _beforeEditContentCB2: function(response, args, record)
    {
        this.callParent(arguments);
        
        if (this.editingPlugin.editing 
            && this.editingPlugin.getActiveColumn().type == 'repeater'
            && (record.data['notEditableData'] === true
                || record.data['notEditableDataIndex'] && Ext.Array.contains(record.data['notEditableDataIndex'], this.forceReadonlyField)))
        {
            let dialog = Ext.getCmp(this.editingPlugin.getActiveEditor().field._dialogId);
            dialog.setReadOnly();
        }
    },
	
	// Override to set edited paths in tree
	_doSaveEdition: function(content, ignoreWarnings, callback)
    {
		var me = this;
		var records = me._findRecords(content.getId());
        var record = records[0]; // we can take the first record since all records should display the same value
            
		var paths = Ext.Array.map(records, r => (this.getNodePath(r)));
		
        var params = {};
        params.values = me._getPrefixedChanges(record, "content.input.");
        params.contentId = me._getContentId(record);
        params.quit = true;
        params['content.view'] = null;
        params['local.only'] = true;
        params['ignore.warnings'] = ignoreWarnings;
		params['paths'] = paths;
        
        Ametys.data.ServerComm.send({
            plugin: 'odf-pilotage', 
            url: 'save-mcc/' + me.workflowEditActionId, 
            parameters: params,
            waitMessage: {
                target: me,
                msg: "{{i18n plugin.cms:CONTENT_EDITION_SAVING}}"
            },
            priority: Ametys.data.ServerComm.PRIORITY_MAJOR, 
            callback: {
                scope: me,
                handler: me._saveEditionCB,
                arguments: {
                    content: content,
                    callback: callback
                }
            }
        });
    },
});