<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    {% set page_title = 'Download Files' %}
    <title>{{ page_title }}</title>

    {% set bloom_mod = 'dewey' %}

</head>
<body>
    {% include 'legacy/bloom_header.html' %}

    <h1>Downloading your files...</h1>
    <div id="debug-output"></div>

    <script type="text/javascript">
        function triggerDownload(url) {
            return new Promise((resolve) => {
                const link = document.createElement('a');
                link.href = url;
                link.download = '';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                resolve();
            });
        }

        async function downloadFiles() {
            const debugOutput = document.getElementById('debug-output');
            let debugHtml = '<p>Download Links:</p><ul>';

            // Trigger file download
            const fileDownloadPath = "{{ file_download_path }}";
            debugHtml += `<li><a href="${fileDownloadPath}" download>${fileDownloadPath}</a></li>`;
            await triggerDownload(fileDownloadPath);

            {% if metadata_download_path %}
            // Trigger metadata file download
            const metadataDownloadPath = "{{ metadata_download_path }}";
            debugHtml += `<li><a href="${metadataDownloadPath}" download>${metadataDownloadPath}</a></li>`;
            await triggerDownload(metadataDownloadPath);
            {% endif %}

            debugHtml += '</ul>';
            debugOutput.innerHTML = debugHtml;

            // After downloads are triggered, redirect to the create file form
            window.location.href = "/dewey";
        }

        // Start the download process
        downloadFiles();
    </script>
</body>
</html>
