var secondClick = false;

function storeCredentials() {
    let usernameInput = document.getElementById('username');
    let passwordInput = document.getElementById('password');
    let jqxhr = $.ajax({
        type: 'GET',
        url: `/api/chat/get/token`,
        headers: {
            "Authorization": "Basic " + btoa(usernameInput.value + ":" + passwordInput.value)
        },
    });
    //this section is executed when the server responds with no error 
    jqxhr.done(function () {
        let authToken = jqxhr.getResponseHeader('X-AUTH-TOKEN');
        localStorage.setItem('authToken', authToken);
        authToken = localStorage.getItem('authToken')
        // console.log("getting header " + authToken);
        // secondClick = true;
        $('#loginForm').submit();

    });
    //this section is executed when the server responds with error
    jqxhr.fail(function () {
        log.error('Error retrieving auth token');
        alertify.error('Error retrieving auth token. Please try again')
        secondClick = false;
        // setTimeout(() => location.reload(), 2000)
    })
    localStorage.setItem('username', usernameInput.value);
}


$('#loginForm').on('submit', function (e) {
    if (!secondClick) {
        secondClick = true;
        e.preventDefault();
        storeCredentials(secondClick);
    }
    // else {
    //     secondClick = false;
    // }
})