base_url = 'http://192.168.178.98:8080'; // http://localhost:8080';
file_path = [];
tree = {};

window.addEventListener('load', function () {
    if (sessionStorage.getItem("authorization") !== null) {
        console.log('Logged in');
        create_base_view();
        create_logout_view();
        url_listener();
        create_tree_view_data('');
    } else {
        console.log('Not logged in');
        create_login_view();
    }
});

window.addEventListener('popstate', function () {
    url_listener();
});

function url_listener() {
    let curr_dir = findGetParameter('path');

    if (curr_dir !== null) {
        if(curr_dir.startsWith('/') || curr_dir === '') {
            httpGetAsync(base_url + curr_dir, null, show_files);
        } else {
            create_error_view('directory does not exist');
        }
    } else {
        httpGetAsync(base_url, null, show_files);
    }
}

function login() {
    let username = document.getElementById("username").value;
    let password = document.getElementById("password").value;

    const xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function () {
        if (this.readyState === 4) {
            if (xmlHttp.status === 200) {
                sessionStorage.setItem("authorization", btoa(username + ':' + JSON.parse(xmlHttp.responseText)['token']));

                create_base_view();
                create_logout_view();
                url_listener();
                create_tree_view_data('');
            }
        }
    }

    xmlHttp.open("POST", base_url + '/login', true);
    xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xmlHttp.send('username=' + username + '&password=' + password);
}

function show_files(response, code) {
    if (code === 200) {
        // OK
        create_file_view(JSON.parse(response));
    } else if (code === 401) {
        // Not logged in
        sessionStorage.removeItem('authorization');
        create_login_view();
    } else {
        // Error
        console.error(code);
        console.error(JSON.parse(response));

        response = JSON.parse(response);
        create_error_view(response['error']);

        // sessionStorage.removeItem('authorization');
        // location.reload();
    }
}

function one_dir_back() {
    let curr_dir = findGetParameter('path');

    if(curr_dir !== null) {
        let dir = curr_dir.split('/');
        dir = dir.slice(0, dir.length - 1);
        curr_dir = dir.join('/');

        return curr_dir;
    }

    return '';
}

function load_file(name, type) {
    let curr_dir = findGetParameter('path');

    if (curr_dir === null) curr_dir = '';

    show_file_view(curr_dir + '/' + name, type);
}