<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Receiver</title>
    <script src="https://cdn.jsdelivr.net/npm/peerjs@1.5.4/dist/peerjs.min.js"></script>
    <style>
        #progress-bar-container {
            margin-top: 20px;
        }

        #progress-bar {
            width: 100%;
            height: 20px;
        }
    </style>
</head>

<body>
    <div id="status">Click the "Download" button to connect and receive the file.</div>
    <button id="download-btn">Download File</button>
    <div id="progress-bar-container" style="display: none;">
        <progress id="progress-bar" value="0" max="100"></progress>
    </div>

    <script>
        window.onload = function () {
            const peer = new Peer(); // Create a PeerJS object
            const status = document.getElementById('status');
            const downloadBtn = document.getElementById('download-btn');
            const progressBarContainer = document.getElementById('progress-bar-container');
            const progressBar = document.getElementById('progress-bar');

            let fileData = []; // Array to store received file chunks
            let fileName = '';
            let totalChunks = 0;
            let receivedChunks = 0;
            let conn;

            // Get 'fileKey' from URL
            const urlParams = new URLSearchParams(window.location.search);
            const fileKey = urlParams.get('fileKey');

            // Ensure 'fileKey' exists
            if (!fileKey) {
                status.innerText = 'No fileKey found in the URL.';
                downloadBtn.style.display = 'none';
                return;
            }

            // Handle download button click to connect and download the file
            downloadBtn.addEventListener('click', () => {
                if (fileKey) {
                    connectToSender(fileKey);
                }
            });

            function connectToSender(fileKey) {
                status.innerText = 'Connecting to the sender...';
                conn = peer.connect(fileKey); // Connect to the peer using fileKey

                conn.on('open', () => {
                    status.innerText = 'Connected to the sender, requesting the file...';
                    conn.send('request-file'); // Request the file from the sender
                    progressBarContainer.style.display = 'block'; // Show progress bar container
                });

                conn.on('data', (data) => {
                    if (data.totalChunks && data.currentChunk !== undefined) {
                        // Receiving file data chunk
                        fileData.push(data.chunk);
                        fileName = data.fileName;
                        totalChunks = data.totalChunks;

                        receivedChunks++;

                        // Update progress bar
                        const progress = (receivedChunks / totalChunks) * 100;
                        progressBar.value = progress;

                        status.innerText = `Receiving file: Chunk ${receivedChunks} of ${totalChunks}`;

                        // Acknowledge receipt of the chunk
                        conn.send('ack');

                        // If all chunks are received
                        if (receivedChunks === totalChunks) {
                            assembleFile();
                        }
                    }
                });

                conn.on('error', () => {
                    status.innerText = 'Connection failed. Please try again.';
                });
            }

            function assembleFile() {
                status.innerText = 'File received. Downloading...';

                // Assemble the complete file from received chunks
                const completeFileData = new Blob(fileData);

                // Trigger the download
                const a = document.createElement('a');
                a.href = URL.createObjectURL(completeFileData);
                a.download = fileName;
                a.click();

                status.innerText = 'File downloaded successfully.';
                progressBarContainer.style.display = 'none'; // Hide progress bar container
                fileData = []; // Reset for next file download
            }
        };
    </script>
</body>

</html>