/**
 * Refresh config button component.
 *
 * @package EaLab\WP_Deployer
 */

const disableAllRefreshButtons = () => {
    const currentRefreshConfigButtonElements = document.querySelectorAll('deploy-sync-content--refresh-config-button');
    currentRefreshConfigButtonElements.forEach((toDisable) => {
        const toDisableButton = toDisable.querySelector('button');
        toDisableButton.dataset.inProgress = 'true';
        toDisableButton.classList.add('disabled');
    });
};

const enableAllRefreshButtons = () => {
    const currentRefreshConfigButtonElements = document.querySelectorAll('deploy-sync-content--refresh-config-button');
    currentRefreshConfigButtonElements.forEach((toEnable) => {
        const toDisableButton = toEnable.querySelector('button');
        delete toDisableButton.dataset.inProgress;
        toDisableButton.classList.remove('disabled');
    });
}

const handle = () => {
    // Retrieve all button elements.
    const refreshConfigButtonElements = document.querySelectorAll('deploy-sync-content--refresh-config-button');

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

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

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

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

            // Disable all refresh buttons.
            disableAllRefreshButtons();

            if (!window.confirm(deploy_sync_content__refreshConfigButton_settings?.text?.confirm ?? 'Are you sure you want to refresh the configuration? This will remove any customized deployment config on this install.')) {
                // Cancel the refresh action.
                statusText.classList.remove('in-progress');

                // Reenable all buttons.
                enableAllRefreshButtons();

                return;
            }

            statusText.classList.add('in-progress');
            statusText.classList.remove('ok', 'not-ok');
            statusText.textContent = deploy_sync_content__refreshConfigButton_settings?.text?.refreshing ?? 'Refreshing the configuration…';

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

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

            if (!url) {
                return;
            }

            fetch(url, {method: 'GET', headers: headers})
                .then((response) => {
                    if (!response.ok) {
                        throw new Error(deploy_sync_content__refreshConfigButton_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__refreshConfigButton_settings?.text?.refreshSuccessful ?? 'The configuration has been refreshed successfully.';

                    statusText.classList.add('ok');
                })
                .catch(() => {
                    statusText.textContent = (deploy_sync_content__refreshConfigButton_settings?.text?.refreshError ?? 'The configuration could not be refreshed.');

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

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

handle();
