// Source: https://blog.mounirmesselmeni.de/2012/11/20/reading-csv-file-with-javascript-and-html5-file-api/
// Source: https://www.js-tutorials.com/javascript-tutorial/reading-csv-file-using-javascript-html5/
// Source: https://stackoverflow.com/questions/13329853/reading-server-file-with-javascript
// Source: https://www.w3schools.com/howto/howto_js_sort_table.asp
// Source: https://stackoverflow.com/questions/19105009/how-to-insert-variables-in-javascript-strings

window.onload = function () {
    handleFile("resources/world_data_v1.csv");
    registerHamburgerToggleClickListener();
};

function handleFile(path) {
    // Check for the various File API support.
    if (window.FileReader) {
        // FileReader are supported.
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.status == 200 && xmlhttp.readyState == 4) {
                processData(xmlhttp.responseText, path);
            }
        };
        xmlhttp.open("GET", path, true);
        xmlhttp.send();
    } else {
        alert('FileReader are not supported in this browser.');
    }
}

function rerequestFile(path, columns) {
    if (window.FileReader) {
        // FileReader are supported.
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.status == 200 && xmlhttp.readyState == 4) {
                updateTable(xmlhttp.responseText, columns);
            }
        };
        xmlhttp.open("GET", path, true);
        xmlhttp.send();
    } else {
        alert('FileReader are not supported in this browser.');
    }
}

function processData(csv, path) {
    var columnAmount = 7;
    var table = "";
    var checkbox = "";

    // split rows
    var allTextLines = csv.split(/\r\n|\n/);

    // create table header
    table += "<thead><tr>";
    checkbox += "<ul>";

    var data = allTextLines[0].split(",");

    for (var j = 0; j < columnAmount; j++) {
        // create table column header
        table += "<th onclick=\"sortTable(" + j + ")\" >";
        table += stringPerToSlash(data[j]);
        table += ' <i class="fas fa-chevron-up"></i>&nbsp;<i class="fas fa-chevron-down"></i>';
        table += "</th>";

        // create dropdown elements
        checkbox += "<li>";
        checkbox += "<input id='" + data[j] + "' type='checkbox' checked='checked' onclick=\"toggleColumn('" + path + "')\"/>";
        checkbox += data[j];
        checkbox += "</li>";
    }

    checkbox += "</ul>";
    table += "</tr></thead><tbody>";

    // create table content
    for (var i = 1; i < allTextLines.length; i++) {
        var data = allTextLines[i].split(',');

        table += "<tr>";

        for (var j = 0; j < columnAmount; j++) {
            table += "<td>";
            table += data[j];
            table += "</td>";
        }

        table += "</tr>";
    }

    table += "</tbody>";

    document.getElementById('t01').innerHTML = table;
    document.getElementById('options').innerHTML = checkbox;
}

function toggleColumn(file) {
    var activated_columns = [];

    /*
    var inner_div = document.getElementById('options').childNodes;

    for (i = 0; i < inner_div.length; i++) {
        var list = inner_div[i].children[0].childNodes;

        for (j = 0; j < list.length; j++) {
            var checkbox = list[j].children[0];

            if (checkbox.checked) {
                activated_columns.push(checkbox.id);
            }
        }
    }
    */

    var list_elements = document.getElementById('options').children[0].childNodes;

    for (i = 0; i < list_elements.length; i++) {
        var element = list_elements[i];
        var checkbox = element.children[0];

        if (checkbox.checked) {
            activated_columns.push(checkbox.id);
        }
    }

    rerequestFile(file, activated_columns);
}


function updateTable(csv, columns) {
    var table = "";

    // split rows
    var allTextLines = csv.split(/\r\n|\n/);

    // create table header
    table += "<tr>";

    var data = allTextLines[0].split(",");
    var discarded_indices = [];

    for (var j = 0; j < data.length; j++) {
        // create table column header
        if (columns.includes(data[j])) {
            table += "<th onclick=\"sortTable(" + j + ")\" >";
            table += data[j];
            table += "</th>";
        } else {
            discarded_indices.push(j);
        }
    }

    // checkbox += "</ul>";
    table += "</tr>";

    // create table content
    for (var i = 1; i < allTextLines.length; i++) {
        var data = allTextLines[i].split(',');

        table += "<tr>";

        for (var j = 0; j < data.length; j++) {
            if (!discarded_indices.includes(j)) {
                table += "<td>";
                table += data[j];
                table += "</td>";
            }
        }

        table += "</tr>";
    }

    document.querySelector('#t01').innerHTML = table;
}

function sortTable(n) {
    var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
    table = document.getElementById("t01");
    switching = true;

    // Set the sorting direction to ascending:
    dir = "asc";

    /* Make a loop that will continue until
    no switching has been done: */
    while (switching) {
        // Start by saying: no switching is done:
        switching = false;
        rows = table.rows;

        /* Loop through all table rows (except the
        first, which contains table headers): */
        for (i = 1; i < (rows.length - 1); i++) {
            // Start by saying there should be no switching:
            shouldSwitch = false;

            /* Get the two elements you want to compare,
            one from current row and one from the next: */
            x = rows[i].getElementsByTagName("td")[n];
            y = rows[i + 1].getElementsByTagName("td")[n];

            var first_element = x.innerHTML.toLowerCase();
            var second_element = y.innerHTML.toLowerCase();

            /* Check if the two rows should switch place,
            based on the direction, asc or desc: */
            if (dir == "asc") {
                // check if the first element is a number, then assume the 
                // second element is also a number
                if (isNaN(first_element)) {
                    if (first_element > second_element) {
                        // If so, mark as a switch and break the loop:
                        shouldSwitch = true;
                        break;
                    }
                } else {
                    if (parseFloat(first_element) > parseFloat(second_element)) {
                        // If so, mark as a switch and break the loop:
                        shouldSwitch = true;
                        break;
                    }
                }
            } else if (dir == "desc") {
                // check if the first element is a number, then assume the 
                // second element is also a number
                if (isNaN(first_element)) {
                    if (first_element < second_element) {
                        // If so, mark as a switch and break the loop:
                        shouldSwitch = true;
                        break;
                    }
                } else {
                    if (parseFloat(first_element) < parseFloat(second_element)) {
                        // If so, mark as a switch and break the loop:
                        shouldSwitch = true;
                        break;
                    }
                }
            }
        }

        if (shouldSwitch) {
            /* If a switch has been marked, make the switch
            and mark that a switch has been done: */
            rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
            switching = true;

            // Each time a switch is done, increase this count by 1:
            switchcount++;
        } else {
            /* If no switching has been done AND the direction is "asc",
            set the direction to "desc" and run the while loop again. */
            if (switchcount == 0 && dir == "asc") {
                dir = "desc";
                switching = true;
            }
        }
    }
}

function stringPerToSlash(columnname) {
    return columnname.includes(" per ") ? columnname.replace(" per ", " / ") : columnname;
}

function registerHamburgerToggleClickListener() {
    let menu = document.querySelector("#menu");
    let header = document.querySelector("#header");
    let section = document.querySelector("#section");
    document.querySelector("#hamburger-toggle").addEventListener('click', function () {
        if (menu.classList.contains('active')) {
            // menu ausblenden
            document.querySelector("#menu").classList.remove('active');
            section.style.marginTop = 0;
        } else {
            // menu einblenden
            document.querySelector("#menu").classList.add('active');
            let height1 = header.clientHeight;
            let height2 = menu.clientHeight;
            section.style.marginTop = height1 + height2 + 10 + 'px'; // + 10 für zusätzlichen abstand (klebt sonst aneinander)
        }


    });
}