document.addEventListener('DOMContentLoaded', async function () {
    const signupButton = document.getElementById('signup');
    const submitButton = document.getElementById('submit');

    const signupDataExists = await window.electronAPI.checkFileExists('signupData.json');
    if (signupDataExists) {
        await window.electronAPI.deleteFile('signupData.json');
    }

    let ip = '';
    await window.electronAPI.readFile('ipConfig.json')
        .then(result => {
            const jsonData = JSON.parse(result.content);
            ip = jsonData.ip;
        })

    const fileExists = await window.electronAPI.checkFileExists('loginData.json');
    if (fileExists) {
        await window.electronAPI.readFile('loginData.json')
            .then(async result => {
                const loginData = JSON.parse(result.content);
                console.log(loginData);
                const {email, password} = loginData;

                await fetch(`http://${ip}/users/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'x-api-key': 'uc_api'
                    },
                    body: JSON.stringify({
                        email: email,
                        password: password
                    })
                }).then(async response => {
                    if (response.ok) {
                        await window.electronAPI.killBeforeLogout();
                        await window.electronAPI.startMainProcesses();
                        fadeOut('main_menu.html');
                    } else {
                        await window.electronAPI.deleteFile('loginData.json');
                    }
                }).catch(error => {
                    console.error(error);
                });
            })
            .catch(async error => {
                console.error('Can\'t read loginData');
                await window.electronAPI.deleteFile('loginData.json');
            });
    }

    signupButton.addEventListener('click', function (e) {
        e.preventDefault();
        console.log('Sign up button clicked.')
        fadeOut('sign_up_profile.html');
    });

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

        const form = document.getElementById('loginForm');
        const formData = new FormData(form);

        const email = formData.get('email');
        const password = formData.get('password');

        await fetch(`http://${ip}/users/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'x-api-key': 'uc_api'
            },
            body: JSON.stringify({
                email: email,
                password: password
            })
        }).then(async response => {
            if (!response.ok) {
                const data = await response.json();
                throw new Error(data.message);
            }

            return response.json();
        }).then(async data => {
            data.data.password = password
            await window.electronAPI.writeFile('loginData.json', JSON.stringify(data.data, null, 2));
            await window.electronAPI.startMainProcesses();
            fadeOut('main_menu.html');
        })
            .catch(async error => {
                await window.electronAPI.showAlert(error.message)
                    .then(() => console.log('Alert window opened'))
                    .catch(error => console.error('Error showing alert:', error));
            })
    });
});
