/**
 * Reindex items button component.
 *
 * @package EaLab\WP_Deployer
 */

const disableAllReindexItemsButtons = () => {
    const currentButtonElements = document.querySelectorAll('deploy-sync-content--reindex-items-button');
    currentButtonElements.forEach((toDisable) => {
        const toDisableButton = toDisable.querySelector('button');
        toDisableButton.dataset.inProgress = 'true';
        toDisableButton.classList.add('disabled');
    });
};

const enableAllReindexItemsButtons = () => {
    const currentButtonElements = document.querySelectorAll('deploy-sync-content--reindex-items-button');
    currentButtonElements.forEach((toEnable) => {
        const toDisableButton = toEnable.querySelector('button');
        delete toDisableButton.dataset.inProgress;
        toDisableButton.classList.remove('disabled');
    });
}

const handleReindexItemsButtons = () => {
    // Retrieve all button elements.
    const reindexItemsButtonElements = document.querySelectorAll('deploy-sync-content--reindex-items-button');

    reindexItemsButtonElements.forEach((reindexItemsButtonElement) => {
        if (reindexItemsButtonElement.getAttribute('data-initialized') === 'true') {
            // The element is already initialized.
            return;
        }

        // Mark the element as initialized.
        reindexItemsButtonElement.setAttribute('data-initialized', 'true');

        const button = reindexItemsButtonElement.querySelector('button');
        const statusText = reindexItemsButtonElement.querySelector('.status-text');

        // Append the action on click on the button.
        button.addEventListener('click', () => {
            if (button.dataset.inProgress) {
                // A request is already in progress.
                // Wait for it to finish.
                return;
            }

            // Disable all reindex buttons.
            disableAllReindexItemsButtons();

            if (!window.confirm(deploy_sync_content__reindexItemsButton_settings?.text?.confirm ?? 'Are you sure you want to re-index items? (Currently indexed items will be preserved.)')) {
                // Cancel the reindex action.
                statusText.classList.remove('in-progress');

                // Reenable all buttons.
                enableAllReindexItemsButtons();

                return;
            }

            statusText.classList.add('in-progress');
            statusText.classList.remove('ok', 'not-ok');
            statusText.textContent = deploy_sync_content__reindexItemsButton_settings?.text?.requestInProgress ?? 'Queueing items for re-indexation…';

            // Add the nonce header to the request.
            const headers = new Headers();
            headers.append('X-WP-Nonce', deploy_sync_content__reindexItemsButton_settings?.rest?.nonce ?? '');

            const url = reindexItemsButtonElement.dataset.url ?? '';

            if (!url) {
                return;
            }

            fetch(url, {method: 'GET', headers: headers})
                .then((response) => {
                    if (!response.ok) {
                        throw new Error(deploy_sync_content__reindexItemsButton_settings?.text?.error ?? 'An error occurred. Please check your network status or the basic Deploy & Sync Content settings, or try again later.');
                    }

                    return response.json();
                })
                .then(() => {
                    statusText.textContent = deploy_sync_content__reindexItemsButton_settings?.text?.reindexSuccessful ?? 'The items have been queued for re-indexation.';

                    statusText.classList.add('ok');
                })
                .catch(() => {
                    statusText.textContent = (deploy_sync_content__reindexItemsButton_settings?.text?.reindexError ?? 'The items could not be re-indexed.');

                    statusText.classList.add('not-ok');
                })
                .finally(() => {
                    statusText.classList.remove('in-progress');

                    // Reenable all buttons.
                    enableAllReindexItemsButtons();
                })
        });
    });
};

handleReindexItemsButtons();
