<table id="assiduiteTable">
    <thead>
        <tr>
            <th>
                <div>
                    <span>Début</span>
                    <a class="icon order" onclick="order('date_debut', assiduiteCallBack, this)"></a>
                </div>
            </th>
            <th>
                <div>
                    <span>Fin</span>
                    <a class="icon order" onclick="order('date_fin', assiduiteCallBack, this)"></a>
                </div>
            </th>
            <th>
                <div>
                    <span>État</span>
                    <a class="icon order" onclick="order('etat', assiduiteCallBack, this)"></a>
                </div>
            </th>
            <th>
                <div>
                    <span>Module</span>
                    <a class="icon order" onclick="order('moduleimpl_id', assiduiteCallBack, this)"></a>
                </div>
            </th>
            <th>
                <div>
                    <span>Justifiée</span>
                    <a class="icon order" onclick="order('est_just', assiduiteCallBack, this)"></a>
                </div>
            </th>
        </tr>
    </thead>
    <tbody id="tableBodyAssiduites">
    </tbody>
</table>
<div id="paginationContainerAssiduites" class="pagination-container">
</div>

<div style="display: none;" id="cache-module">
    {% include "assiduites/widgets/moduleimpl_dynamic_selector.j2" %}
</div>

<script>
    const paginationContainerAssiduites = document.getElementById("paginationContainerAssiduites");
    let currentPageAssiduites = 1;
    let orderAssiduites = true;
    let filterAssiduites = {
        columns: [
            "entry_date", "date_debut", "date_fin", "etat", "moduleimpl_id", "est_just"
        ],
        filters: {}
    }
    const tableBodyAssiduites = document.getElementById("tableBodyAssiduites");

    function assiduiteCallBack(assi) {
        assi = filterArray(assi, filterAssiduites.filters)
        renderTableAssiduites(currentPageAssiduites, assi);
        renderPaginationButtons(assi);

        try { stats() } catch (_) { }
    }



    function renderTableAssiduites(page, assiduités) {

        generateTableHead(filterAssiduites.columns, true)

        tableBodyAssiduites.innerHTML = "";
        const start = (page - 1) * itemsPerPage;
        const end = start + itemsPerPage;

        assiduités.slice(start, end).forEach((assiduite) => {
            const row = document.createElement("tr");
            row.setAttribute('type', "assiduite");
            row.setAttribute('obj_id', assiduite.assiduite_id);

            const etat = assiduite.etat.toLowerCase();
            row.classList.add(`l-${etat}`);
            filterAssiduites.columns.forEach((k) => {
                const td = document.createElement('td');
                if (k.indexOf('date') != -1) {
                    td.textContent = moment.tz(assiduite[k], TIMEZONE).format(`DD/MM/Y HH:mm`)
                } else if (k.indexOf("module") != -1) {
                    td.textContent = getModuleImpl(assiduite);
                } else if (k.indexOf('est_just') != -1) {
                    td.textContent = assiduite[k] ? "Oui" : "Non"
                } else {
                    td.textContent = assiduite[k].capitalize()
                }

                row.appendChild(td)
            })


            row.addEventListener("contextmenu", openContext);

            tableBodyAssiduites.appendChild(row);
        });
        updateActivePaginationButton();
    }

    function detailAssiduites(assiduite_id) {
        const path = getUrl() + `/api/assiduite/${assiduite_id}`;
        async_get(
            path,
            (data) => {
                const user = getUser(data);
                const module = getModuleImpl(data);

                const date_debut = moment.tz(data.date_debut, TIMEZONE).format("DD/MM/YYYY HH:mm");
                const date_fin = moment.tz(data.date_fin, TIMEZONE).format("DD/MM/YYYY HH:mm");
                const entry_date = moment.tz(data.entry_date, TIMEZONE).format("DD/MM/YYYY HH:mm");

                const etat = data.etat.capitalize();
                const desc = data.desc == null ? "" : data.desc;
                const id = data.assiduite_id;
                const est_just = data.est_just ? "Oui" : "Non";

                const html = `
                <div class="obj-detail">
                    <div class="obj-dates">
                        <div id="date_debut" class="obj-part">
                        <span class="obj-title">Date de début</span>
                        <span class="obj-content">${date_debut}</span>
                        </div>
                        <div id="date_fin" class="obj-part">
                        <span class="obj-title">Date de fin</span>
                        <span class="obj-content">${date_fin}</span>
                        </div>
                        <div id="entry_date" class="obj-part">
                        <span class="obj-title">Date de saisie</span>
                        <span class="obj-content">${entry_date}</span>
                        </div>
                    </div>

                    <div class="obj-mod">
                        <div id="module" class="obj-part">
                        <span class="obj-title">Module</span>
                        <span class="obj-content">${module}</span>
                        </div>
                        <div id="etat" class="obj-part">
                        <span class="obj-title">Etat</span>
                        <span class="obj-content">${etat}</span>
                        </div>
                        <div id="user" class="obj-part">
                        <span class="obj-title">Créée par</span>
                        <span class="obj-content">${user}</span>
                        </div>
                    </div>
                    <div class="obj-rest">
                        <div id="est_just" class="obj-part">
                        <span class="obj-title">Justifié</span>
                        <span class="obj-content">${est_just}</span>
                        </div>
                        <div id="desc" class="obj-part">
                        <span class="obj-title">Description</span>
                        <p class="obj-content">${desc}</p>
                        </div>
                        <div id="id" class="obj-part">
                        <span class="obj-title">Identifiant de l'assiduité</span>
                        <span class="obj-content">${id}</span>
                        </div>
                    </div>
                    </div>

                `

                const el = document.createElement('div');
                el.innerHTML = html;

                openAlertModal("Détails", el.firstElementChild, null, "green")
            }
        )
    }


    function editionAssiduites(assiduite_id) {
        const path = getUrl() + `/api/assiduite/${assiduite_id}`;
        async_get(
            path,
            (data) => {
                let module = data.moduleimpl_id;
                if (
                    module == null && data.hasOwnProperty("external_data") &&
                    data.external_data != null &&
                    data.external_data.hasOwnProperty('module')
                ) {
                    module = data.external_data.module.toLowerCase();
                }

                const etat = data.etat;
                let desc = data.desc == null ? "" : data.desc;
                const html = `
                    <div class="assi-edit">
                        <div class="assi-edit-part">
                            <legend>État de l'assiduité</legend>
                            <select name="etat" id="etat">
                                <option value="present">Présent</option>
                                <option value="retard">En Retard</option>
                                <option value="absent">Absent</option>
                            </select>
                        </div>
                        <div class="assi-edit-part">
                            <legend>Module</legend>
                            <select name="module" id="module">
                            </select>
                        </div>
                        <div class="assi-edit-part">
                            <legend>Description</legend>
                            <textarea name="desc" id="desc" cols="50" rows="10" maxlength="500"></textarea>
                        </div>
                    </div>
                
                `

                const el = document.createElement('div')
                el.innerHTML = html;
                const assiEdit = el.firstElementChild;

                assiEdit.querySelector('#etat').value = etat.toLowerCase();
                assiEdit.querySelector('#desc').value = desc != null ? desc : "";
                updateSelect(module, '#moduleimpl_select', "2022-09-04")
                assiEdit.querySelector('#module').replaceWith(document.querySelector('#moduleimpl_select').cloneNode(true));
                openPromptModal("Modification de l'assiduité", assiEdit, () => {
                    const prompt = document.querySelector('.assi-edit');
                    const etat = prompt.querySelector('#etat').value;
                    const desc = prompt.querySelector('#desc').value;
                    let module = prompt.querySelector('#moduleimpl_select').value;
                    let edit = {
                        "etat": etat,
                        "desc": desc,
                        "external_data": data.external_data
                    }

                    edit = setModuleImplId(edit, module);

                    fullEditAssiduites(data.assiduite_id, edit, () => {
                        loadAll();
                    })


                }, () => { }, "green");
            }
        );
    }

    function fullEditAssiduites(assiduite_id, obj, call = () => { }) {
        const path = getUrl() + `/api/assiduite/${assiduite_id}/edit`;
        async_post(
            path,
            obj,
            call,
            (data, status) => {
                //error
                console.error(data, status);
                errorAlert();
            }
        );
    }
</script>