// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Cascading category → course → devoir picker for the évaluation form
 * (classes/form/eval_form.php, "Devoir Moodle" source type): the course and
 * devoir selects start with a single placeholder option and are filled via
 * the plugin's read-only web services only once their parent select has a
 * real value, instead of the form listing every course/assignment on the
 * site up front.
 *
 * The devoir select (kid-assign-cmid) is display-only — its name attribute
 * is "cmid_picker", not "cmid" — because Moodle's own quickform select
 * silently drops any submitted value that wasn't one of the <option>s
 * declared server-side when the form was built, which would always be true
 * here since real options only ever get added by this module. The actual
 * "cmid" field submitted with the form is a plain hidden input
 * (kid-assign-cmid-value) that this module keeps in sync instead.
 *
 * @module     local_kid/eval_devoir_picker
 * @copyright  2026 INSP
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
import Ajax from 'core/ajax';
import Notification from 'core/notification';

const SELECTORS = {
    CATEGORY: '[data-role="kid-assign-category"]',
    COURSE: '[data-role="kid-assign-course"]',
    CMID_PICKER: '[data-role="kid-assign-cmid"]',
    CMID_VALUE: '[data-role="kid-assign-cmid-value"]',
};

/**
 * Replaces a select's options with a single placeholder.
 *
 * @param {Element} select
 * @param {String} text
 */
const resetSelect = (select, text) => {
    select.innerHTML = '';
    const placeholder = document.createElement('option');
    placeholder.value = '0';
    placeholder.textContent = text;
    select.appendChild(placeholder);
};

/**
 * Replaces a select's options with its "ready" placeholder followed by the
 * fetched items.
 *
 * @param {Element} select
 * @param {Array} items
 * @param {String} valueKey
 * @param {String} labelKey
 */
const populateSelect = (select, items, valueKey, labelKey) => {
    resetSelect(select, select.dataset.placeholderReady);
    items.forEach((item) => {
        const option = document.createElement('option');
        option.value = item[valueKey];
        option.textContent = item[labelKey];
        select.appendChild(option);
    });
};

/**
 * Entry point, called once by pages/eval_edit.php when adding a new
 * évaluation (the cascade only exists on that form, never when editing).
 */
export const init = () => {
    const categorySelect = document.querySelector(SELECTORS.CATEGORY);
    const courseSelect = document.querySelector(SELECTORS.COURSE);
    const cmidPicker = document.querySelector(SELECTORS.CMID_PICKER);
    const cmidValue = document.querySelector(SELECTORS.CMID_VALUE);
    if (!categorySelect || !courseSelect || !cmidPicker || !cmidValue) {
        return;
    }

    // Captured once, before any repopulation, so "changer la catégorie"
    // can put the devoir/course selects back exactly how they started.
    const courseInitialText = courseSelect.options[0].textContent;
    const cmidInitialText = cmidPicker.options[0].textContent;

    const resetCmid = (text) => {
        resetSelect(cmidPicker, text);
        cmidValue.value = '0';
    };

    categorySelect.addEventListener('change', () => {
        resetCmid(cmidInitialText);

        const categoryid = parseInt(categorySelect.value, 10);
        if (!categoryid) {
            resetSelect(courseSelect, courseInitialText);
            return;
        }

        Ajax.call([{
            methodname: 'local_kid_get_courses_for_category',
            args: {categoryid},
        }])[0]
        .then((data) => populateSelect(courseSelect, data.courses, 'id', 'fullname'))
        .catch(Notification.exception);
    });

    courseSelect.addEventListener('change', () => {
        const courseid = parseInt(courseSelect.value, 10);
        if (!courseid) {
            resetCmid(cmidInitialText);
            return;
        }

        Ajax.call([{
            methodname: 'local_kid_get_assigns_for_course',
            args: {courseid},
        }])[0]
        .then((data) => {
            populateSelect(cmidPicker, data.assigns, 'cmid', 'name');
            cmidValue.value = '0';
            return data;
        })
        .catch(Notification.exception);
    });

    cmidPicker.addEventListener('change', () => {
        cmidValue.value = cmidPicker.value;
    });
};
