document.addEventListener('DOMContentLoaded', async function () {
    await insertUsername();
    setInterval(loadReceivedFiles, 3000); // Call loadReceivedFiles every 5000 ms (5 seconds)

    const backupButton = document.getElementById('backup');
    const shareButton = document.getElementById('share_dir');

    const manageDepartmentButton = document.getElementById('manage_department');
    const manageUsersButton = document.getElementById('manage_users');
    const changeInfoButton = document.getElementById('change_info');
    const shareFileButton = document.getElementById('share_file');
    const decryptButton = document.getElementById('decrypt');
    const logoutButton = document.getElementById('logout');

    async function loadReceivedFiles() {
        const checkFileReceived = await window.electronAPI.checkFileExists('filesReceived.json');
        if (!checkFileReceived) {
            return;
        }

        try {
            const fileData = await window.electronAPI.readFile('filesReceived.json');
            const filesJson = JSON.parse(fileData.content);
            const receivedFiles = filesJson.receivedFiles;

            const notificationsDiv = document.getElementById('notifications');
            const existingButtons = Array.from(notificationsDiv.children).map(button => button.getAttribute('data-filepath'));

            receivedFiles.forEach(filePath => {
                // Check if the button for this file path already exists
                if (!existingButtons.includes(filePath)) {
                    const button = document.createElement('button');
                    button.setAttribute('data-filepath', filePath); // Set a custom attribute to track the file path
                    button.name = 'notification';
                    button.textContent = 'You received a file';
                    button.addEventListener('click', () => handleFileReceivedButtonPressed(filePath, button));
                    notificationsDiv.appendChild(button);
                }
            });
        } catch (error) {
            console.error('Error loading received files:', error);
        }
    }

    async function handleFileReceivedButtonPressed(filePath, button) {
        console.log('Notification button clicked!');

        // Open file in file explorer
        await window.electronAPI.showFileInExplorer(filePath)
            .then(() => console.log('File explorer opened'))
            .catch(error => console.error('Error opening file explorer:', error));

        // Remove the button
        button.remove();

        // Call to remove the path from the JSON file
        await window.electronAPI.removePathFromReceivedFiles(filePath)
            .then(() => console.log('Path removed from received files'))
            .catch(error => console.error('Error removing path:', error));
    }


    checkDirBackupFileExists()
        .then(() => console.log('verificare backupDir facuta'));

    checkShareDirFileExists()
        .then(() => console.log('verificare ShareDir facuta'));

    backupButton.addEventListener('click', function () {
        console.log('Set backup directory button clicked!');

        window.electronAPI.openJsonDirConfigDialog('dirBackup.json')
            .then(() => console.log('Back-up directory set'))
            .catch(async error => await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error)));
    });

    shareButton.addEventListener('click', function () {
        console.log('Set backup directory button clicked!');

        window.electronAPI.openJsonDirConfigDialog('dirShare.json')
            .then(() => console.log('Back-up directory set'))
            .catch(async error => await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error)));
    });

    manageUsersButton.addEventListener('click', async function(){
        fadeOut('manage_users.html');
    });

    changeInfoButton.addEventListener('click', function () {
        console.log('Change your info button clicked!');
        fadeOut('profile.html');
    });

    decryptButton.addEventListener('click', function () {
        fadeOut('decrypting_backup.html');
    });

    changeInfoButton.addEventListener('click', function () {
        console.log('Change your info button clicked!');
        fadeOut('profile.html');
    });

    shareFileButton.addEventListener('click', function () {
        console.log('Share a file button clicked!');
        fadeOut('share_file.html');
    });

    manageDepartmentButton.addEventListener('click', function() {
        fadeOut('manage_departments.html');
    })

    logoutButton.addEventListener('click', async function () {
        console.log('Logout button clicked!');
        await window.electronAPI.killBeforeLogout();
        await window.electronAPI.deleteFile('loginData.json');
        fadeOut('login.html');
    });

    decryptButton.addEventListener('click', async function (){

    });
    async function checkDirBackupFileExists() {
        try {
            // Make an IPC call to check file existence
            const fileExists = await window.electronAPI.checkFileExists('dirBackup.json');

            if (!fileExists) {
                const notificationsDiv = document.getElementById('notifications');
                const button = document.createElement('button');
                button.id = 'backup_alert';
                button.name = 'alert';
                button.textContent = 'Set your backup directory!';
                button.addEventListener('click', handleBackupButtonPressed);
                notificationsDiv.appendChild(button);
            }
        } catch (error) {
            console.error('Error checking file existence:', error);
        }
    }

    async function checkShareDirFileExists() {
        try {
            const fileExists = await window.electronAPI.checkFileExists('dirShare.json');

            if (!fileExists) {
                const notificationsDiv = document.getElementById('notifications');
                const button = document.createElement('button');
                button.id = 'share_file_alert';
                button.name = 'alert';
                button.textContent = 'Set your share directory!';
                button.addEventListener('click', handleShareButtonPressed);
                notificationsDiv.appendChild(button);
            }
        } catch (error) {
            console.error('Error checking file existence:', error);
        }
    }

    async function handleBackupButtonPressed() {
        console.log('Button clicked!');

        await window.electronAPI.openJsonDirConfigDialog('dirBackup.json')
            .then(() => console.log('Back-up directory set'))
            .catch(async error => await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error)));

        const button = document.getElementById('backup_alert');
        button.remove();
    }

    async function handleShareButtonPressed() {
        console.log('Button clicked!');

        await window.electronAPI.openJsonDirConfigDialog('dirShare.json')
            .then(() => console.log('Share directory set'))
            .catch(async error => await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error)));

        const button = document.getElementById('share_alert');
        button.remove();
    }

    async function insertUsername() {
        try {
            const userData = await window.electronAPI.readFile('loginData.json');
            const userJson = JSON.parse(userData.content);
            const username = userJson.name;

            const usernameField = document.getElementById('username_field');
            if (usernameField) {
                usernameField.textContent = username + '!';
            }
        } catch (error) {
            console.error('Error loading username:', error);
            const usernameField = document.getElementById('username_field');
            usernameField.textContent = 'User!';
        }
    }
});
