function htmlToElem(html) {
    let temp = document.createElement('template');
    html = html.trim(); // Never return a space text node as a result
    temp.innerHTML = html;
    return temp.content.firstChild;
}

function dateFormat(input) {
    if (input) {
        var dt = new Date(input);
        return dt.toLocaleDateString("fr-CH");
    }
    return '-';
}

var changed = false;

function check_changed(ev) {
    if (changed) {
        alert("Vos données n'ont pas été sauvegardées !");
        ev.preventDefault();
        return false;
    }
}

function toggle_read_more(ev) {
    ev.preventDefault();
    const link = ev.target;
    link.innerHTML = (link.innerHTML == 'Afficher la suite') ? 'Réduire' : 'Afficher la suite';
    link.parentNode.querySelector('.long').classList.toggle('hidden');
    link.parentNode.querySelector('.short').classList.toggle('hidden');
}

function showImage(ev) {
    var modal = document.getElementById('imgModal'); /* Present in base.html */
    var imgTag = document.getElementById("img01");
    var captionText = document.getElementById("caption");
    ev.preventDefault();
    modal.style.display = "block";
    imgTag.src = this.href;
    captionText.innerHTML = this.textContent;
}

function setConfirmHandlers(section) {
    if (typeof section === 'undefined') section = document;
    const selector = section.querySelectorAll(".btn-danger, .confirm");
    selector.forEach(button => {
        button.addEventListener('click', ev => {
            if (button.dataset.confirm) {
                ev.preventDefault();
                if (!confirm(button.dataset.confirm)) {
                    return false;
                } else {
                    if (button.getAttribute('formaction')) button.form.action = button.formAction;
                    button.form.submit();
                }
            }
        });
    });
}

function openFormInModal(url) {
    const popup = document.querySelector('#popup0');

    function setupForm() {
        DateTimeShortcuts.init(popup);
        setConfirmHandlers(popup);
        document.querySelectorAll("#popup0 form").forEach((form) => {
            form.addEventListener('submit', (ev) => {
                ev.preventDefault();
                const form = ev.target;
                const formData = new FormData(form);
                // GET/POST with fetch
                let url = form.action;
                let params = {method: form.method};
                if (form.method == 'post') {
                    params['body'] = formData;
                }
                fetch(url, params).then(res => {
                    if (res.redirected) {
                        window.location.reload(true);
                        return '';
                    }
                    return res.text();
                }).then(html => {
                    if (html) {
                        // Redisplay form with errors or display confirm page
                        popup.querySelector('.modal-body').innerHTML = html;
                        setupForm();
                    }
                }).catch((err) => {
                    console.log(err);
                    alert("Désolé, une erreur s'est produite");
                });
            });
        });
    }

    return fetch(url).then(res => res.text()).then(html => {
        const modal = new bootstrap.Modal(popup);
        popup.querySelector('.modal-body').innerHTML = html;
        modal.show();
        setupForm();
        return popup;
    });
}

function resetForm(ev) {
    const form = ev.target.closest('form');
    Array.from(form.elements).forEach(el => { el.value = ''; });
    form.submit();
}

function submitFilterForm(form) {
    let action = form.action || '.';
    const formData = new FormData(form);
    action += '?' + new URLSearchParams(formData).toString();
    fetch(action, {
        method: 'get',
        headers: {'X-Requested-With': 'Fetch'}
    }).then(response => { return response.text(); }).then(output => {
        const parser = new DOMParser();
        const doc = parser.parseFromString(output, "text/html");
        const tableBody = doc.querySelector('.table-sortable tbody');
        document.querySelector('.table-sortable tbody').replaceWith(tableBody);
        const pagination = doc.querySelector('#pagination');
        document.querySelector('#pagination').replaceWith(pagination);
    });
}

function sortColumn(ev) {
    const header = ev.target;
    const form = document.querySelector('.selection_form');
    const desc = header.classList.contains('asc');
    form.elements['sort_by'].value = (desc ? '-' : '') + header.dataset.col;
    submitFilterForm(form);
    // Reset colums classes
    Array.from(header.parentNode.children).forEach(head => {
        head.classList.remove('desc');
        head.classList.remove('asc');
    });
    header.classList.add(desc ? 'desc': 'asc');
}

document.addEventListener("DOMContentLoaded", () => {
    if (typeof DateTimeShortcuts !== 'undefined') {
        DateTimeShortcuts.init();
    }
    autosize(document.querySelectorAll('textarea'));
    $("form").not(".selection_form").not("[method='get']").change(function() {
        changed = true;
    });
    $("#menu_crne, #aemo_buttons, #aemo_print_buttons").click
    (check_changed);
    setConfirmHandlers();
    $("table.sortable").each(function(idx) {
        new Tablesort(this);
    });
    $(".table-sortable th").click(sortColumn);
    $('a.read_more').click(toggle_read_more);

    // Attachment images
    $('a.image').click(showImage);
    $('#modalClose').click(function(ev) {$(this).closest('div').hide(); });

    $('input[name=dh_debut_1]').change(function(){
        var dateFin = $('input[name=dh_fin_0]');
        if (dateFin.val() == '') {
            // Copier date de début vers date de fin
            dateFin.val($('input[name=dh_debut_0]').val());
        }
        var heureFin = $('input[name=dh_fin_1]');
        if (heureFin.val() == '') {
            // Mettre heure de fin 1 heure après heure de début
            var dh = $('input[name=dh_debut_1]').val().split(":");
            h = parseInt(dh[0]) + 1;
            heureFin.val(h.toString() + ":" + dh[1]);
        }
    });

    document.querySelectorAll('.immediate-submit').forEach(immediate => {
        //immediate.addEventListener('click', immediateSubmit);
        // With screen readers, users don't click but change the radio value
        immediate.addEventListener('change', (ev) => {
            ev.target.form.submit()
        });
    });

    $(".js-add, .js-edit").click(function(e) {
        const url = this.dataset.url || this.href;
        e.preventDefault();
        openFormInModal(url);
        return false;
    });

    // Activation des tooltips
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    tooltipTriggerList.map((el) => new bootstrap.Tooltip(el));

    $('#reset-button').click(resetForm);
});

function debounce(func, timeout=300) {
  let timer;
  return (...args) => {
    if (timeout <= 0) func.apply(this, args);
    else {
      clearTimeout(timer);
      timer = setTimeout(() => { func.apply(this, args); }, timeout);
    }
  };
}

async function archiveFamilies(ev) {
    const btn = ev.target;
    const archiveUrl = btn.dataset.archiveurl;
    const counterSpan = document.querySelector('#archive-counter');
    const totalSpan = document.querySelector('#archive-total');

    bootstrap.Modal.getInstance(document.getElementById('archiveModal')).hide();
    document.getElementById('archive-message').removeAttribute('hidden');
    const resp = await fetch(btn.dataset.getarchivableurl);
    const data = await resp.json();
    let compteur = 0;
    totalSpan.textContent = data.length;
    const formData = new FormData();
    formData.append('csrfmiddlewaretoken', document.querySelector('[name=csrfmiddlewaretoken]').value);
    for (let i = 0; i < data.length; i++) {
        const archResp = await fetch(
            archiveUrl.replace('999', data[i]),
            {method: 'POST', headers: {'X-Requested-With': 'Fetch'}, body: formData}
        );
        const jsonResp = await archResp.json();
        compteur += 1;
        counterSpan.textContent = compteur;
    }
    const messageP = document.querySelector("#archive-message p");
    messageP.textContent = `${compteur} dossiers ont été archivés avec succès.`;
    messageP.classList.remove('alert-danger');
    messageP.classList.add('alert-success');
}
