<div>
    {% if label != false%}
    <label for="moduleimpl_select">
        Module
    </label>
    {% else %}
    {% endif %}
    {% if moduleid %}
    <select id="{{moduleid}}" class="dynaSelect">
        {% include "assiduites/widgets/simplemoduleimpl_select.j2" %}
    </select>
    {% else %}
    <select id="moduleimpl_select" class="dynaSelect">
        {% include "assiduites/widgets/simplemoduleimpl_select.j2" %}
    </select>
    {% endif %}

    <div id="saved" style="display: none;">
        {% include "assiduites/widgets/simplemoduleimpl_select.j2" %}
    </div>
</div>


<script>

    function getEtudFormSemestres() {
        let semestre = {};
        sync_get(getUrl() + `/api/etudiant/etudid/${etudid}/formsemestres`, (data) => {
            semestre = data;
        });
        return semestre;
    }

    function filterFormSemestres(semestres, dateIso) {
        const date = new Date(Date.removeUTC(dateIso));
        semestres = semestres.filter((fm) => {
            return date.isBetween(new Date(Date.removeUTC(fm.date_debut_iso)), new Date(Date.removeUTC(fm.date_fin_iso)), '[]');
        })

        return semestres;
    }

    function getFormSemestreProgramme(fm_id) {
        let semestre = {};
        sync_get(getUrl() + `/api/formsemestre/${fm_id}/programme`, (data) => {
            semestre = data;
        });
        return semestre;
    }

    function getModulesImplByFormsemestre(semestres) {
        const map = new Map();

        semestres.forEach((fm) => {
            const array = [];

            const fm_p = getFormSemestreProgramme(fm.formsemestre_id);
            ["ressources", "saes", "modules"].forEach((r) => {
                if (r in fm_p) {
                    fm_p[r].forEach((o) => {
                        array.push(getModuleInfos(o))
                    })
                }
            })

            map.set(fm.titre_num, array)
        })

        return map;
    }

    function getModuleInfos(obj) {
        return {
            moduleimpl_id: obj.moduleimpl_id,
            titre: obj.module.titre,
            code: obj.module.code,
        }
    }


    function populateSelect(sems, selected, query) {
        const select = document.querySelector(query);
        select.innerHTML = document.getElementById('saved').innerHTML
        sems.forEach((mods, label) => {
            const optGrp = document.createElement('optgroup');
            optGrp.label = label

            mods.forEach((obj) => {
                const opt = document.createElement('option');
                opt.value = obj.moduleimpl_id;
                opt.textContent = `${obj.code} ${obj.titre}`
                if (obj.moduleimpl_id == selected) {
                    opt.setAttribute('selected', 'true');
                }

                optGrp.appendChild(opt);
            })
            select.appendChild(optGrp);
        })
        if (selected === "autre") {
            select.querySelector('option[value="autre"]').setAttribute('selected', 'true');
        }
    }

    function updateSelect(moduleimpl_id, query = "#moduleimpl_select", dateIso = null) {
        let sem = getEtudFormSemestres()
        if (!dateIso) {
            dateIso = getDate().format("YYYY-MM-DD")
        }

        sem = filterFormSemestres(sem, dateIso)
        const mod = getModulesImplByFormsemestre(sem)
        populateSelect(mod, moduleimpl_id, query);
    }

    function updateSelectedSelect(moduleimpl_id, query = "#moduleimpl_select") {
        const mod_id = moduleimpl_id != null ? moduleimpl_id : ""
        document.querySelector(query).value = `${mod_id}`.toLowerCase();
    }


    {% if moduleid %}
    const moduleimpl_dynamic_selector_id = "{{moduleid}}"
    {% else %}
    const moduleimpl_dynamic_selector_id = "moduleimpl_select"

    {% endif %}



    window.addEventListener("load", () => {
        document.getElementById(moduleimpl_dynamic_selector_id).addEventListener('change', (el) => {
            const assi = getCurrentAssiduite(etudid);
            if (assi) {
                editAssiduite(assi.assiduite_id, assi.etat, [assi]);
            }
        })

        try {
            const conflicts = getAssiduitesConflict(etudid);
            if (conflicts.length > 0) {
                updateSelectedSelect(getCurrentAssiduiteModuleImplId());
            }
        } catch { }
    }, { once: true });



</script>

<style>
    #moduleimpl_select {
        width: 125px;
        text-overflow: ellipsis;
    }
</style>