function login() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    fetch('/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`,
    })
    .then(response => {
        if (response.ok) {
            document.getElementById('login-form').style.display = 'none';
            document.getElementById('config-form').style.display = 'block';
            loadConfig();
        } else {
            alert('Login failed. Please try again.');
        }
    })
    .catch(error => console.error('Error:', error));
}

function loadConfig() {
    fetch('/config')
    .then(response => response.json())
    .then(config => {
        document.getElementById('server_address').value = config.server_address;
        document.getElementById('max_retries').value = config.max_retries;
        document.getElementById('reconnect_interval').value = config.reconnect_interval;
        document.getElementById('read_timeout').value = config.read_timeout;
        document.getElementById('rest_api_endpoint').value = config.rest_api_endpoint;
    })
    .catch(error => console.error('Error:', error));
}

document.getElementById('config-update-form').addEventListener('submit', function(e) {
    e.preventDefault();

    const config = {
        server_address: document.getElementById('server_address').value,
        max_retries: parseInt(document.getElementById('max_retries').value),
        reconnect_interval: parseInt(document.getElementById('reconnect_interval').value),
        read_timeout: parseInt(document.getElementById('read_timeout').value),
        rest_api_endpoint: document.getElementById('rest_api_endpoint').value,
    };

    fetch('/config', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(config),
    })
    .then(response => {
        if (response.ok) {
            alert('Configuration updated successfully');
        } else {
            alert('Failed to update configuration');
        }
    })
    .catch(error => console.error('Error:', error));
});