document.addEventListener("DOMContentLoaded", async function () {
    async function performUploads() {
        try {
            const uploadFile = await window.electronAPI.readFile('usersDestTemp.json');
            const uploadData = JSON.parse(uploadFile.content);

            const uploadPromises = uploadData.users.map(async (user) => {
                try {
                    const fileResponse = await fetch(uploadData.filePath);
                    if (!fileResponse.ok) {
                        throw new Error(`HTTP error when trying to fetch the file: status ${fileResponse.statusText}`);
                    }
                    const fileBlob = await fileResponse.blob();

                    await timeout(5000); // Timeout to simulate delay or wait
                    const url = `http://${user.destIp}:${user.destPort}/share_file`;

                    const uploadResponse = await fetch(url, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/octet-stream',
                            'X-IdUser': user.userId,
                            'X-NameOfFile': user.fileName,
                            'X-SizeOfFile': fileBlob.size
                        },
                        body: fileBlob
                    });

                    if (!uploadResponse.ok) {
                        const response = await uploadResponse.json();
                        throw new Error(`HTTP error during file upload to ${user.userId}: status ${response.message}`);
                    }

                    return {userId: user.userId, success: true, message: `Upload successful for user ${user.userId}`};
                } catch (error) {
                    console.error(`Failed to upload for user ${user.userId}:`, error);
                    return {userId: user.userId, success: false, message: `Upload failed for user ${user.userId}`};
                }
            });

            const results = await Promise.all(uploadPromises);
            results.forEach(result => {
                if (result.success) {
                    console.log(result.message);
                } else {
                    console.error(result.message);
                }
            });
            console.log('All files processed. Check the console for detailed results.');
        } catch (error) {
            console.error('An error occurred during uploads:', error);
        } finally {
            await window.electronAPI.deleteFile('usersDestTemp.json');
        }
    }

    function timeout(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    await performUploads();
    await timeout(3000);
    fadeOut('main_menu.html'); // Make sure this function is properly defined or available in your context
});

