document.addEventListener("DOMContentLoaded", async function () {
    let pathToFile = '';
    let serverIp = '';
    await window.electronAPI.readFile('ipConfig.json')
        .then(result => {
            const jsonData = JSON.parse(result.content);
            serverIp = jsonData.ip;
        })

    function updateFileName() {
        const fileNameElement = document.getElementById('fileName');
        if (pathToFile.trim() === '') {
            fileNameElement.textContent = 'No file chosen';
        } else {
            fileNameElement.textContent = pathToFile.split('\\').pop().split('/').pop();
        }
    }

    updateFileName();

    async function fetchUsersAndCreateCheckboxes() {
        const result = await window.electronAPI.readFile('loginData.json');
        const loginData = JSON.parse(result.content);

        const {id} = loginData;

        fetch(`http://${serverIp}/users`, {
            method: 'GET',
            headers: {
                'x-api-key': 'uc_api'
            }
        })
            .then(response => response.json())
            .then(data => {
                const usersDiv = document.querySelector('.choose_user_form_content');
                usersDiv.innerHTML = '';
                data['data'].forEach(user => {
                    if (user.id !== id) {
                        const checkbox = document.createElement('input');
                        checkbox.type = 'checkbox';
                        checkbox.name = 'users';
                        checkbox.value = user.id;

                        const label = document.createElement('label');
                        label.innerHTML = `${user.name}`;
                        label.insertBefore(checkbox, label.firstChild); // Insert checkbox before the label's first child

                        usersDiv.appendChild(label);
                    }
                });
            })
            .catch(error => console.error('Error fetching users:', error));
    }

    document.getElementById('selectFile').addEventListener('click', async function () {
        console.log('Select file button clicked');

        try {
            pathToFile = await window.electronAPI.openFileDialog();
            updateFileName();
        } catch (error) {
            console.error('Error opening file dialog:', error);
        }
    });

    document.getElementById('backButton').addEventListener('click', async function () {
        console.log('Back button clicked');
        fadeOut('main_menu.html');
    });

    document.getElementById('submitButton').addEventListener('click', async function (event) {
        event.preventDefault();
        console.log('Submit button clicked');

        // Check if pathToFile has content
        if (!pathToFile.trim()) {
            await window.electronAPI.showAlert('File not chosen!')
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error));
            return;
        }

        const form = document.getElementById('userDestForm');
        const checkboxes = form.querySelectorAll('input[name="users"]');
        const selectedUserIds = Array.from(checkboxes)
            .filter(checkbox => checkbox.checked)
            .map(checkbox => checkbox.value);

        if (!selectedUserIds.length) {
            await window.electronAPI.showAlert('No user selected!')
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error));
            return;
        }

        const uploadData = {
            filePath: pathToFile, // Use the pathToFile variable
            users: []
        };

        for (const userId of selectedUserIds) {
            try {
                const ipResponse = await fetch(`http://${serverIp}/backup_schemes/${userId}`,{
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'x-api-key': 'uc_api',
                    }
                });
                if (!ipResponse.ok) {
                    throw new Error(`Failed to fetch IP address for user ${userId}: status ${ipResponse.status}`);
                }
                const { data: destIp } = await ipResponse.json();
                uploadData.users.push({
                    userId,
                    destIp,
                    destPort: 3000,  // Static destination port
                    fileName: pathToFile.split('\\').pop().split('/').pop()
                });
            } catch (error) {
                console.error('Error fetching user data:', error);
            }
        }

        window.electronAPI.writeFile('usersDestTemp.json', JSON.stringify(uploadData, null, 2))
            .then(async () => {
                console.log('File saved successfully');
                fadeOut('sending_file_confirmation.html');
            })
            .catch(error => console.error('Failed to save file:', error));
    });

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


    fetchUsersAndCreateCheckboxes().then(() => console.log('Page rendered'))
});
