function create_login_view() {
    let tmp = document.createElement('div');
    tmp.innerHTML = `<div id="login">
                <form>
                    <h1>Login</h1>
                    <div>
                        <label for="username"></label>
                        <input type="text" name="username" id="username" placeholder="Username" value="admin">
                    </div>
                    <div>
                        <label for="password"></label>
                        <input type="password" name="password" id="password" placeholder="Password" value="admin">
                    </div>
                    <div>
                        <button type="button" value="Login" onclick="login();">Login</button>
                    </div>
                </form>
            </div>`;
    document.getElementById("wrapper").innerHTML = '';
    document.getElementById("wrapper").appendChild(tmp.firstChild);
}

function create_logout_view() {
    let logout = document.createElement('div');
    logout.classList.add('logout');
    logout.innerText = 'Logout';
    logout.onclick = function () {
        sessionStorage.removeItem('authorization');
        location.reload();
    }
    document.getElementsByClassName('app-header')[0].appendChild(logout);
}

function create_base_view() {
    let tmp = document.createElement('div');
    tmp.innerHTML = `<div id="tree"></div>
        <div id="files"></div>`;

    document.getElementById("wrapper").innerHTML = tmp.innerHTML;
}

function create_tree_view_data(curr_dir) {
    let url = base_url + curr_dir;

    const xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function () {
        if (this.readyState === 4) {
            if (xmlHttp.status === 200) {
                let data = JSON.parse(xmlHttp.responseText);

                for (let i = 0; i < data.length; i++) {
                    if (data[i]['Type'] === 'dir') {
                        file_path.push(curr_dir + '/' + data[i]['Name']);
                        create_tree_view_data(curr_dir + '/' + data[i]['Name']);
                    }
                }

                tree = file_path.reduce((arr, path) => addPath(path.split('/'), arr), [])[0]['children'];
                create_tree_view();
            }
        }
    }

    xmlHttp.open("GET", url, true);
    xmlHttp.setRequestHeader('Authorization', 'Basic ' + sessionStorage.getItem('authorization'));
    xmlHttp.send(null);
}

function addPath(pathcomponents, arr ){
    let component = pathcomponents.shift()
    let comp = arr.find(item => item.text === component)
    if (!comp) {
        comp =  {text: component}
        arr.push(comp)
    }
    if(pathcomponents.length){
        addPath(pathcomponents, comp.children || (comp.children = []))
    }
    return arr
}

function create_tree_view() {
    let tree = document.createElement('div');
    tree.innerHTML = `<ul id="tree_ul"></ul> `;

    document.getElementById("tree").innerHTML = '';
    create_list_view(this.tree, document.getElementById("tree"), '');

    // Remove nested-class from root element
    document.getElementsByTagName('ul')[0].classList.remove('nested')

    let toggler = document.getElementsByClassName("folder");
    for (let i = 0; i < toggler.length; i++) {
        toggler[i].addEventListener("click", function () {
            if(this.parentElement.querySelector(".nested") !== null) {
                this.parentElement.querySelector(".nested").classList.toggle("active");
            }
            this.classList.toggle("folder-open");
        });
    }
}

function tree_onclick(url) {
    window.history.pushState('index', 'Filemanager', 'index.html?path=' + url);
    url_listener();
}

function create_list_view(dataRoot, elementRoot, url) {
    if (dataRoot) {
        const list = document.createElement('ul');
        list.classList.add('nested');
        elementRoot.appendChild(list);

        Object.keys(dataRoot).forEach(key => {
            // // Create a text node and a list element to put it in
            const listElement = document.createElement('li');
            listElement.innerHTML = `<span class="folder" onclick="tree_onclick('${url}/${dataRoot[key].text}');">${dataRoot[key].text}</span>`;
            list.appendChild(listElement);

            // Continue recursively down now using the current list element
            create_list_view(dataRoot[key]['children'], listElement, url + '/' + dataRoot[key].text);
        });
    }
}

function create_file_view(data) {
    let curr_dir = findGetParameter('path');

    let files = document.createElement('div');
    files.innerHTML = `<div id="path"></div>
        <table>
            <thead>
                <tr>
                    <th></th>
                    <th>Name</th>
                    <th>Type</th>
                </tr>
            </thead>
            <tbody>
                <tr id="back" style="cursor: pointer" onclick="window.history.pushState('index', 'Filemanager', 'index.html?path=' + one_dir_back()); url_listener()">
                    <td data-order="___"></td>
                    <td>..</td>
                    <td></td>
                </tr>    
            </tbody>
        </table>`;

    // Folders
    for (let i = 0; i < data.length; i++) {
        if (data[i]['Type'] === 'dir') {
            let folder = document.createElement('tr');
            folder.style = 'cursor: pointer;';
            folder.onclick = function () {
                if (curr_dir === null) curr_dir = '';
                window.history.pushState('index', 'Filemanager', 'index.html?path=' + curr_dir + '/' + data[i]['Name']);
                url_listener();
            };
            folder.innerHTML = `<td data-order="__"><span class="material-icon">folder</span></td>
                    <td>${data[i]['Name']}</td>
                    <td>directory</td>`;
            files.getElementsByTagName('tbody')[0].appendChild(folder);
        }
    }

    // Files
    for (let i = 0; i < data.length; i++) {
        if (data[i]['Type'] !== 'dir') {
            let file = document.createElement('tr');
            file.style = 'cursor: pointer;';
            file.onclick = function () {
                load_file(data[i]['Name'], data[i]['Type']);
            };

            let icon = 'article';
            if (data[i]['Type'].indexOf("application") >= 0) {
                icon = 'apps';
            } else if (data[i]['Type'].indexOf("audio") >= 0) {
                icon = 'music_note';
            } else if (data[i]['Type'].indexOf("drawing") >= 0) {
                icon = 'gesture';
            } else if (data[i]['Type'].indexOf("image") >= 0) {
                icon = 'image';
            } else if (data[i]['Type'].indexOf("message") >= 0) {
                icon = 'mail';
            } else if (data[i]['Type'].indexOf("multipart") >= 0) {
                icon = 'note_add';
            } else if (data[i]['Type'].indexOf("text") >= 0) {
                icon = 'description';
            } else if (data[i]['Type'].indexOf("video") >= 0) {
                icon = 'movie';
            }

            file.innerHTML = `<td data-order="__"><span class="material-icon">${icon}</span></td>
                    <td>${data[i]['Name']}</td>
                    <td>${data[i]['Type']}</td>`;

            file.addEventListener("contextmenu", function(e) {
                document.getElementById('custom-menu').style.display = 'block';
                document.getElementById('custom-menu').style.left = e.pageX + 'px';
                document.getElementById('custom-menu').style.top = e.pageY + 'px';
                console.log(this.innerHTML.split('<td>')[1].split('</td>')[0]);
                e.preventDefault();
            });

            files.getElementsByTagName('tbody')[0].appendChild(file);
        }
    }

    // Path
    let s = `<div onclick="window.history.pushState('index', 'Filemanager', 'index.html?path='); url_listener()" class="arrow-pointer" style="z-index: 1000"><span>/</span></div>`;

    if (curr_dir !== null) {
        let folders = curr_dir.split('/');
        for (let i = 1; i < folders.length; i++) {
            s = s.concat(`<div onclick="window.history.pushState('index', 'Filemanager', 'index.html?path=${folders.slice(0, i + 1).join('/')}'); url_listener()" class="arrow-pointer" style="z-index: ${folders.length - i}"><span>${folders[i]}</span></div>`);
        }
    }
    files.getElementsByTagName('div')[0].innerHTML = s;

    document.getElementById("files").innerHTML = '';
    document.getElementById("files").appendChild(files);

    // Close contextmenu
    document.getElementsByTagName('body')[0].addEventListener('click', function () {
        document.getElementById('custom-menu').style.display = 'none';
    });
}

function create_error_view(text) {
    let error = document.createElement('div');
    error.innerHTML = `<div class="error">
            <span class="text">${text}. Go <span style="cursor:pointer;" onclick="window.history.back(); document.getElementById('error_wrapper').innerHTML = '';">back</span></span>
            <span><i class="material-icons" onclick="document.getElementById('error_wrapper').innerHTML = '';">close</i></span>
        </div>`;

    document.getElementById('error_wrapper').appendChild(error.firstChild);
}

function show_file_view(data, type) {
    let modal = document.getElementById("file_view");
    let title = document.getElementById("file_title");
    let modal_content = document.getElementsByClassName("modal-content")[0];


    if (type.indexOf("application") >= 0) {
        modal_content.innerHTML = ``;
    } else if (type.indexOf("audio") >= 0) {
        httpGetAsync(base_url + data + '?format=base64', null, show_audio_data);
    } else if (type.indexOf("drawing") >= 0) {
        modal_content.innerHTML = ``;
    } else if (type.indexOf("image") >= 0) {
        httpGetAsync(base_url + data + '?format=base64', null, show_image_data);
    } else if (type.indexOf("message") >= 0) {
        modal_content.innerHTML = ``;
    } else if (type.indexOf("multipart") >= 0) {
        modal_content.innerHTML = ``;
    } else if (type.indexOf("text") >= 0) {
        httpGetAsync(base_url + data, null, show_text_data);
    } else if (type.indexOf("video") >= 0) {
        httpGetAsync(base_url + data + '?format=base64', null, show_video_data);
    } else if (type.indexOf("workbook") >= 0) {
        modal_content.innerHTML = ``;
    } else if (type.indexOf("x-world") >= 0) {
        modal_content.innerHTML = ``;
    } else {
        modal_content.innerHTML = ``;
    }

    title.innerText = `File: ${data}`;

    modal.style.display = "block";
}

function show_image_data(response, code) {
    if (code === 200) {
        document.getElementsByClassName("modal-content")[0].innerHTML = `<img style="width: 100%" src="data:image/png;base64, ${response}" alt="Image">`;
    } else {
        console.log(code + " " + response);
    }
}

function show_text_data(response, code) {
    if (code === 200) {
        document.getElementsByClassName("modal-content")[0].innerHTML = `<textarea style="width: calc(100% - 8px); height: 90%">${response}</textarea>
        <button type="button" value="Save">Save</button>
        <button type="button" value="SaveAs">Save As</button>
        <button type="button" value="Discard">Discard</button>`;
    } else {
        console.log(code + " " + response);
    }
}

function show_audio_data(response, code) {
    if (code === 200) {
        document.getElementsByClassName("modal-content")[0].innerHTML = `<audio controls>
            <source src="data:audio;base64, ${response}">
                Your browser does not support the audio element.
        </audio>`;
    } else {
        console.log(code + " " + response);
    }
}

function show_video_data(response, code) {
    if (code === 200) {
        document.getElementsByClassName("modal-content")[0].innerHTML = `<video controls style="width: 100%;">
            <source src="data:video;base64, ${response}">
                Your browser does not support the audio element.
        </video>`;
    } else {
        console.log(code + " " + response);
    }
}