/*
 *  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 is used to select a MCC modalite filtered by regime.
 */
Ext.define('Ametys.plugins.odfpilotage.widget.Notes', {
    extend : 'Ametys.form.AbstractFieldsWrapper',
    
    layout: 'fit',
    
    items: [{ 
        xtype: 'container',     
        cls: 'notes-widget',
        layout: {
            type: 'vbox',
            align: 'stretch'
        }
    }],
      
     getErrors: function(value) {
     var myLocalErrors = [];
     // compute errors
     return Ext.Array.merge(this.callParent(arguments), myLocalErrors);
     },
      
     setValue: function(value) {
        let grid = this.ownerCt.ownerCmp;
        let editingContext = grid.editingPlugin.context;
        let record = editingContext.record;
        let educationalPath = record.getPath("contentId", ";").substring(1);
                
        let container = this.items.get(0);
         
        function _addSession(session)
        {
            if (!value[session])
            {
                return;
            }
            
            // Session
            let sessionInserted = false;
            
            let i = 0;
            for (let n of Object.keys(value[session].data))
            {
                let d = value[session].data[n];
                if (d.common || d.path ==   educationalPath)
                {
                    // Evaluation
                    let evaluationInserted = false;
    
                    let j = 0;
                    for (let note of d.notes)
                    {
                        if (!sessionInserted)
                        {
                            container.add(Ext.create('Ext.Component', {height:24, cls:'session'}));
                            sessionInserted = true;
                        }
                        
                        if (!evaluationInserted)
                        {
                            container.add(Ext.create('Ext.Component', {height:24, cls:'evaluation'}));
                            evaluationInserted = true;
                        }
                        
                        // Note
                        container.add(Ext.create('Ametys.form.widget.Number', {
                            cls: 'note',
                            note: session + "/" + i + "/" + j,
                            minValue: 0.01,
                            maxValue: 100,
                            height: 24,
                            style: {
                                marginBottom: 0
                            },
                            value: d.common ? note[educationalPath] : note[""]
                        }));
                        j++;
                    }
                    i++;
                }
            }
        }
        
        // Change the fields depending on the current value
        container.removeAll();
        
        if (value != null)
        {
            container.add(Ext.create('Ext.Component', {height:24, cls:'course'}));
            
            _addSession("mccSession1");
            _addSession("mccSession2");
        }
        
        let me = this;
        window.setTimeout(function() {
            container.updateLayout();
            if (grid.getPlugins()[0].activeEditor)
            {
                grid.getPlugins()[0].activeEditor.realign();
                let field = container.down("field" + (Ametys.plugins.odf.pilotage.tool.MicroSkillsWeightTool._OVER_INDEX ? "[note='" + Ametys.plugins.odf.pilotage.tool.MicroSkillsWeightTool._OVER_INDEX + "']" : ""));
                if (field)
                {
                    field.focus();
                }
            }
        }, 1);

        // split the value between items
        this._value = value;
     },
      
     getValue: function() {
        // return the value composed by items
        let newValue = window.structuredClone(this._value);
        if (!newValue)
        {
            return newValue;
        }
        
        let grid = this.ownerCt.ownerCmp;
        let editingContext = grid.editingPlugin.context;
        let record = editingContext.record;
        let educationalPath = record.getPath("contentId", ";").substring(1);
                
        let container = this.items.get(0);
        let fields = container.query("field");
        let index = 0;
        
        let atLeastOneChange = false;
        atLeastOneChange = _getValue("mccSession1") || atLeastOneChange;
        atLeastOneChange = _getValue("mccSession2") || atLeastOneChange;
        
        // we compute this._value to return the same pointer if nothing changed to avoid that the grid thinks that there is a modification
        return atLeastOneChange ? newValue : this._value;
        
        function _getValue(session)
        {
            let atLeastOneChange = false;
            
            if (!newValue[session])
            {
                return atLeastOneChange;
            }

            for (let n of Object.keys(newValue[session].data))
            {
                let d = newValue[session].data[n];
                if (d.common || d.path ==   educationalPath)
                {
                    for (let note of d.notes)
                    {
                        let v = fields[index].validate() ? fields[index].getValue() : null;
                        
                        if ((d.common ? note[educationalPath] : note[""]) != v)
                        {
                            atLeastOneChange = true;
                            note[d.common ? educationalPath : ""] = v;
                        }
                        index++;
                    }
                }
            }
            
            return atLeastOneChange;
        }
     }
});