export const entityForm = () => {
    // Initialization
    initializeSubmitForm();
    disableSubmitButtonsOnSubmit();
};

function initializeSubmitForm() {
    let formSaveButton = document.querySelector('#entity_form #admin_content_submit');
    let submitButtonFake = document.getElementById('submit_fake');

    if (formSaveButton && submitButtonFake) {
        submitButtonFake.addEventListener('click', function (e) {
            e.preventDefault();
            submitButtonFake.title = 'Sauvegarde en cours...';

            formSaveButton.click();
        });
    } else if (submitButtonFake) {
        submitButtonFake.title = 'Sauvegarde automatique';
        submitButtonFake.classList.add('btn-secondary');
        submitButtonFake.classList.remove('btn-success');
        submitButtonFake.style.cursor = 'not-allowed';
        submitButtonFake.addEventListener('click', function (e) {
            e.preventDefault();
        });
    }
}

function disableSubmitButtonsOnSubmit() {
    const forms = document.querySelectorAll("form");
    forms.forEach((form) => {
        form.addEventListener("submit", function () {
            setTimeout(() => {
                const submitButtons = form.querySelectorAll("[type=submit]");
                submitButtons.forEach((button) => {
                    button.disabled = true;
                });
            }, 10);
        });
    });
}
