const dayMap = {
    "Lundi": 0,
    "Mardi": 1,
    "Mercredi": 2,
    "Jeudi": 3,
    "Vendredi": 4,
    "Samedi": 5,
    "Dimanche": 6
};


// ======================================================
// Cours ajoutés manuellement
// ======================================================

function addCourse(course = {}) {
    const tbody = document.getElementById("courses");

    const row = document.createElement("tr");

    row.innerHTML = `
        <td>
            <input type="checkbox" class="select-row" checked>
        </td>

        <td>
            <select class="day">
                <option value="0">Lundi</option>
                <option value="1">Mardi</option>
                <option value="2">Mercredi</option>
                <option value="3">Jeudi</option>
                <option value="4">Vendredi</option>
            </select>
        </td>

        <td><input class="start" type="time"></td>
        <td><input class="end" type="time"></td>
        <td><input class="name"></td>
        <td><input class="prof"></td>
        <td><input class="room"></td>
        <td><input class="color" type="color"></td>

        <td>
            <button type="button" class="remove">
                ❌
            </button>
        </td>
    `;

    tbody.appendChild(row);


    row.querySelector(".day").value = course.day ?? 0;
    row.querySelector(".start").value = course.start ?? "";
    row.querySelector(".end").value = course.end ?? "";
    row.querySelector(".name").value = course.name ?? "";
    row.querySelector(".prof").value = course.prof ?? "";
    row.querySelector(".room").value = course.room ?? "";
    row.querySelector(".color").value =
        course.color ?? "#80b3ff";


    row.querySelector(".remove").onclick = () => {
        row.remove();
    };
}


// ======================================================
// Gestion des UE fondamentales
// ======================================================

const fonda =
    [...document.querySelectorAll(
        "#courses-base .ue-selector"
    )];


fonda.forEach(cb => {

    cb.addEventListener("change", () => {

        const selected =
            fonda.filter(x => x.checked);

        /*
        if (selected.length > 2) {
            cb.checked = false;
            alert("Choisissez seulement 2 UE parmi les 3.");
        }
            */


        updateTD();
    });

});



function updateTD() {

    document
        .querySelectorAll(
            "#courses-base input[type=radio]"
        )
        .forEach(radio => {

            const ue =
                radio.dataset.ue;


            const selected =
                document.querySelector(
                    `.ue-selector[data-ue="${ue}"]`
                )?.checked;


            radio.disabled = !selected;


            if (!selected)
                radio.checked = false;
        });
}


// ======================================================
// Conversion d'une ligne HTML en cours JSON
// ======================================================

function rowToCourse(row) {
    return {

        day:
            Number(row.dataset.day),

        start:
            row.dataset.start,

        end:
            row.dataset.end,

        name:
            row.dataset.name ?? "",

        prof:
            row.dataset.prof ?? "",

        room:
            row.dataset.room ?? "",

        color:
            row.dataset.color ?? "#ffffff"
    };
}



// ======================================================
// Extraction des cours fixes
// ======================================================

function extractFixedCourses(container) {

    const courses = [];


    container
        .querySelectorAll("tr")
        .forEach(row => {
            //console.log(row);

            const checkbox =
                document.getElementById(row.getAttribute("checkbox-id"))

            enabled = checkbox.checked;

            if (!enabled)
                return;

            const course =
                rowToCourse(row);
            console.log(course);


            if (course)
                courses.push(course);

        });


    return courses;
}


// ======================================================
// Submit PDF
// ======================================================

document
    .getElementById("courseForm")
    .addEventListener(
        "submit",
        async e => {

            e.preventDefault();


            let cours = [];


            cours.push(
                ...extractFixedCourses(
                    document.getElementById(
                        "courses-base"
                    )
                )
            );


            cours.push(
                ...extractFixedCourses(
                    document.getElementById(
                        "courses-autre"
                    )
                )
            );



            // Cours ajoutés manuellement

            document
                .querySelectorAll(
                    "#courses tr"
                )
                .forEach(row => {


                    if (
                        !row.querySelector(
                            ".select-row"
                        ).checked
                    )
                        return;


                    cours.push({

                        day:
                            Number(
                                row.querySelector(
                                    ".day"
                                ).value
                            ),

                        start:
                            row.querySelector(
                                ".start"
                            ).value,

                        end:
                            row.querySelector(
                                ".end"
                            ).value,

                        name:
                            row.querySelector(
                                ".name"
                            ).value,

                        prof:
                            row.querySelector(
                                ".prof"
                            ).value,

                        room:
                            row.querySelector(
                                ".room"
                            ).value,

                        color:
                            row.querySelector(
                                ".color"
                            ).value
                    });

                });



            const submitButton = document.getElementById("submit-button");

            const loader =
                document.querySelector(".loader");

            const frame =
                document.getElementById("img_svg");

            const pdflink =
                document.getElementById("pdf_link");


            submitButton.disabled = true;
            loader.style.display = "block";
            pdflink.disabled = true;

            try {

                const response_svg =
                    await fetch("/edt.svg", {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json"
                        },
                        body: JSON.stringify({ cours })
                    });

                if (!response_svg.ok)
                    throw new Error("Erreur lors de la génération du SVG.");

                const blob_svg =
                    await response_svg.blob();

                const url_svg =
                    URL.createObjectURL(blob_svg);


                frame.src = url_svg;
                frame.style.display = "block";


                const response =
                    await fetch("/edt.pdf", {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json"
                        },
                        body: JSON.stringify({ cours })
                    });

                if (!response.ok)
                    throw new Error("Erreur lors de la génération du PDF.");

                const blob =
                    await response.blob();

                const url =
                    URL.createObjectURL(blob);

                pdflink.href = url;
                pdflink.style.display = "block";

            } catch (err) {

                console.error(err);
                alert(err.message);

            } finally {

                loader.style.display = "none";
                submitButton.disabled = false;
		pdflink.disabled = false;

            }

        }
    );



// ======================================================
// Select all cours ajoutés
// ======================================================

const selectAll =
    document.getElementById(
        "select-all"
    );


if (selectAll) {

    selectAll.onchange = () => {

        document
            .querySelectorAll(
                ".select-row"
            )
            .forEach(cb => {
                cb.checked =
                    selectAll.checked;
            });

    };
}
