/*
 *  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 provides a widget to select one or more micro skills from a program in MCC in courses.<br>
 */
Ext.define('Ametys.odf.widget.SelectMCCSkills', {
    extend: 'Ametys.odf.widget.SelectProgramItemOfSameContext',
    
    boxMinHeight: 500,
    
    /**
     * @cfg {String} [isCommonField] The path to a relative field that indicate the if the evaluation is mutualised
     */
    
    /**
     * @cfg {String} [educationalPathField] The path to a relative field that stores the educational path of the course in the case where the isCommonField value is 'false'
     */
    
    /**
     * @cfg {String} [skillEducationalPathField] The path to a relative field that stores the educational path of this skill
     */
    
    /**
     * @cfg {String} [skillAttachedCourseSearchField] The name of the search field to use to restrict the search based on the educational path
     */
    
    constructor: function (config)
    {
        config.allowCreation = false;
        config.modelId = 'search-ui.mcc-microskills';
        config.limitToContextLanguage = false;
        
        this.educationalPathRecieved = config.contentInfo.educationalPath;
        
        this.callParent(arguments);
    },
    
    initEvents: function()
    {
        this.callParent(arguments);
        
        let me = this;
        // Following code require that all the relative fields are created, so we have to "wait"
        window.setTimeout(function() {
            // If an educational path was provided in the content info, set the program id from it
            if (this.educationalPathRecieved)
            {
                // Set the program id from the course program
                me._setEducationalPathFromPath();
            }
            else
            {
                let isCommon = Ametys.form.Widget.getRelativeValue(me.isCommonField, me, {silently : true});
                // If the field exists, the others will too, so add the listeners on them to update the program id when they change
                if (isCommon !== undefined)
                {
                    // When one of the two fields is changed, update the program id field
                    Ametys.form.Widget.onRelativeValueChange(me.isCommonField, me, me._setEducationalPathFromPath, me);
                    Ametys.form.Widget.onRelativeValueChange(me.educationalPathField, me, me._setEducationalPathFromPath, me);
                    Ametys.form.Widget.onRelativeValueChange(me.skillEducationalPathField, me, me._setEducationalPathFromPath, me);
                }
                else
                {
                    // If the field does not exist, it means we are in a context where the course is not shared
                    // In this case, retrieve the program id from the course id
                    me._setEducationalPathFromPath();
                }
            }
        }, 1);
    },
    
    _getAdditionalLoadValues: function()
    {
        var values = this.callParent(arguments);
        
        // Only load compatible micro skills for the path
        if (this.educationalPath)
        {
            values[this.skillAttachedCourseSearchField] = this.educationalPath;
        }
        
        return values;
    },
    
    _setEducationalPathFromPath: function()
    {
        let educationalPath;
        if (this.educationalPathRecieved)
        {
            educationalPath = this.educationalPathRecieved;
        }
        else
        {
            let isCommon = Ametys.form.Widget.getRelativeValue(this.isCommonField, this, {silently : true});
            
            // If the field does not exist, the others won't either
            if (isCommon !== undefined)
            {
                // If course is shared and evaluation is shared, try to retrieve the path from the skill educational path field
                if (isCommon)
                {
                    educationalPath = Ametys.form.Widget.getRelativeValue(this.skillEducationalPathField, this);
                }
                // If course is shared but evaluation is not shared, try to retrieve the path from the parent educational path field
                else if (!isCommon)
                {
                    // Retrieve the path from the parent repeater
                    educationalPath = Ametys.form.Widget.getRelativeValue(this.educationalPathField, this);
                }
            }
        }
        
        // If no program was found, retrieve it from the course id
        // This can happen in grid mode, because we have the fields but they can be empty
        if (educationalPath)
        {
            this._setEducationalPathFromPathCb(educationalPath);
        }
        else
        {
            Ametys.data.ServerComm.callMethod({
                role: "org.ametys.plugins.odfpilotage.helper.MCCCourseTreeGridHelper",
                methodName: "getCourseEducationalPath",
                parameters: [this.contentInfo.contentId],
                callback: {
                    handler: this._setEducationalPathFromPathCb,
                    scope: this
                },
                errorMessage:true,
                waitMessage: false
            });
        }
    },
    
    _setEducationalPathFromPathCb: function(educationalPath)
    {
        // If the field is initializing, don't reset the value of the field, only set the program Id (which is supposed to be coherent with the value)
        if (this.educationalPath === undefined)
        {
            this.educationalPath = educationalPath;
            // Delete lastQuery to force load of store next time the combo is expanded
            delete this.combobox.lastQuery;
            
            if (!educationalPath)
            {
                // This is not supposed to happen (maybe if the course is not attached to any program)
                this.disable();
            }
        }    
        else if (!educationalPath)
        {
            this.educationalPath = educationalPath;
            // This is not supposed to happen (only case is if the course is not attached to any program)
            this.disable();
        }
        // If the program selected has changed, the field needs to be updated
        else if (this.educationalPath != educationalPath)
        {
            this.educationalPath = educationalPath;
            this.enable();
            // Reset the value of the field because the selected program has changed
            this.reset();
            // Delete lastQuery to force load of store next time the combo is expanded
            delete this.combobox.lastQuery;
        }
    }
})