document.addEventListener('DOMContentLoaded', async function () {

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

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

    const emailInput = document.querySelector('input[name="email"]');
    const usernameInput = document.querySelector('input[name="username"]');
    const passwordInput = document.querySelector('input[name="password"]');

    emailInput.value = loginData.email;
    usernameInput.value = loginData.name;
    passwordInput.value = loginData.password;

    const backButton = document.querySelector('button[name="login"]');
    const submitButton = document.querySelector('button[name="submit"]');

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

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

        const emailInput = document.querySelector('input[name="email"]');
        const usernameInput = document.querySelector('input[name="username"]');
        const passwordInput = document.querySelector('input[name="password"]');

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

        const {id, department} = loginData;
        const email = emailInput.value;
        const name = usernameInput.value;
        const password = passwordInput.value;

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

            await window.electronAPI.writeFile('loginData.json', JSON.stringify({
                id: id,
                name: name,
                email: email,
                password: password,
                department: department
            }));

            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));
        })
    });
});
