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

/**
 * This class edit values in repeaters by educational path.
 * Works only in grid edition with the MCCCourseTool#renderRepeaterByEducationalPath
 */
Ext.define('Ametys.plugins.odfpilotage.widget.RepeaterValueByEducationalPath', {
    extend : 'Ametys.form.AbstractFieldsWrapper',
    
    initComponent: function() 
    {
        this.items = [
            Ext.applyIf({ 
                flex: 1 
            }, this.getInitialConfig().innerWidget) 
        ];
        
        this.callParent();
    },
    
    /**
     * Get the wrapped field
     * @return {Ext.form.field.Field} the field
     */
    getValueField: function()
    {
        return this.items.get(0);
    },
    
    _getValueFromRepeater: function(repeaterValue)
    {
        repeaterValue = repeaterValue || this.value;
        
        let educationalPath = this._getEducationalPath(repeaterValue);
        if (!educationalPath)
        {
            return null;
        }
        
        let me = this;
        let matching = repeaterValue.entries.filter(a => a.values[me.pathField] == educationalPath);
        if (matching.length == 0)
        {
            return null;
        }
        
        return matching[0].values[this.valueField];
    },
    
    _getEducationalPath: function(value)
    {
        value = value || this.value;
        
        return value && value._educationalPath ? value._educationalPath[this._getCurrentRecord().getId()] : null;
    },
    
    _computeUpdatedValue: function(fieldValue, force)
    {
        let me = this;
        
        let typeValue = this.value;
        if (!typeValue)
        {
            return typeValue;
        }
        
        let value = Ext.clone(typeValue);
        if (this._recordId 
            && (force || this.ownerCt.ownerCmp.editingPlugin.editing))
        {
            let educationalPath = this._getEducationalPath();
            
            let oldFieldValue = this._getValueFromRepeater();

            if (oldFieldValue !== null && fieldValue !== null) // Existing value modified
            {
                value.entries.filter(a => a.values[me.pathField] == educationalPath)[0].values[this.valueField] = fieldValue;
            }
            else if (oldFieldValue !== null) // Existing value removed
            {
                value.entries = value.entries.filter(a => a.values[me.pathField] != educationalPath);
            }
            else if (fieldValue !== null) // New value
            {
                let v = {};
                v[this.valueField] = fieldValue;
                v[this.pathField] = educationalPath;
                
                value.entries.push({values: v});   
            }
            
            for (let i = 0; i < value.entries.length; i++) 
            {
                value.entries[i].position = i + 1;
            }
        }
        
        return value;
    },
    
    getValue: function()
    {
        let typedUpdatedValue = this._computeUpdatedValue(this.getValueField().getValue(), false);
        if (!typedUpdatedValue)
        {
            return typedUpdatedValue;
        }
        
        let entries = {};
        Ametys.plugins.cms.search.SearchGridHelper._explodeRepeater(entries, this._getCurrentRecord(), typedUpdatedValue, "");
        
        this._lastValues = this._lastValues || {};
        this._lastValues[JSON.stringify(entries)] = typedUpdatedValue;
        
        return entries;
    },

    setValue: function(value)
    {
        this._addListener();
        
        let typedValue = this._getCurrentRecord().getData()[this.column.dataIndex + "_repeater"];
        this.callParent([typedValue]);
        
        this.getValueField().setValue(this._getValueFromRepeater());
        
        this._recordId = this._getCurrentRecord().getId(); 
    },
    
    _onEdit: function(editingPlugin, context)
    {
        if (context.column.dataIndex == this.column.dataIndex)
        {
            // Really changing value to the second reperter record value
            let record = this._getCurrentRecord();
            
            let typedUpdatedValue = this._lastValues[JSON.stringify(record.getData()[this.column.dataIndex])];
            
            let oldTypedValue = this._getCurrentRecord().get(this.column.dataIndex + "_repeater");
            if (JSON.stringify(typedUpdatedValue) != JSON.stringify(oldTypedValue)) // avoid setting the same value that would be marked as changed 
            {
                this._getCurrentRecord().set(this.column.dataIndex + "_repeater", typedUpdatedValue);
            }
        }
    },
    
    _addListener: function() 
    {
        if (!this._listenerAdded)
        {
            let grid = this.ownerCt.ownerCmp;
            grid.editingPlugin.on('edit', this._onEdit, this);
            
            this._listenerAdded = true;
        }
    },
    
    /**
     * @private
     * Get the recordId associated to the current edition
     */
    _getCurrentRecord: function() 
    {
        if (this.ownerCt)
        {
            let grid = this.ownerCt.ownerCmp;
            let editingContext = grid.editingPlugin.context;
            let record = editingContext.record;
            
            return record;
        }
        else
        {
            return null;
        }
    }
});