
function getCheckdStatistics() {
    let checkList = document.querySelectorAll("#statistics input[type=checkbox]");
    let ret = "";
    for (let box of checkList) {
        if (box["checked"]) {
            ret = ret + box.getAttribute("name") + "=on&";
        }
    }
    ret = ret.substring(0, ret.length - 1);
    return ret;
}

async function getStatistics() {
    let req = getCheckdStatistics();
    let fetchOption = {
        method: "GET",
        credentials: "same-origin",
        headers: {
            "Accept": "application/json",
        }
    };

    let ret = await fetch("/output/statistics/?" + req, fetchOption)
        .then(res => {
            if (res.ok) {
                return res.json();
            } else {
                console.log("No statistics");
                return false;
            }
        });
    return ret;
}

function processStatistics(data) {
    clearSection();
    for (let key in data) {
        let xData = [];
        let yData = [];
        let dataPairs = data[key].split("\n");
        for (let pair of dataPairs) {
            let xyData = pair.split(" ");
            //xData.push(xyData[0]);
            xData.push(Number.parseFloat(xyData[0]).toFixed(3));    //XXX Data should be rounded with chart options.
            yData.push(xyData[1]);
        }
        initGraph(key, xData, yData);
    }
}

function clearSection() {
    let sec = document.querySelector("section");
    let elementList = document.querySelectorAll("section > *");
    for (let element of elementList) {
        sec.removeChild(element);
    }
}

function initGraph(metric, xData, yData) {
    let sec = document.querySelector("section");

    let canva = document.createElement("canvas");
    canva.id = metric;
    //canva.style.backgroundColor = "red";
    sec.appendChild(canva);

    let canva2D = canva.getContext("2d");

    new Chart(canva2D, {
        type: "bar",
        data: {
            labels: xData,
            //labels: ["100", "200"],
            datasets: [{
                label: metric,
                data: yData,
                backgroundColor: [
                    "rgb(0, 100, 239)"
                ]
            }]
        },
        options: {
            scales: {
                xAxis: {
                    ticks: {
                        maxTicksLimit: 25
                    }
                }
            }
        }
    })
}

async function initStatistics() {
    let data = await getStatistics();
    processStatistics(data);
}

function init() {
    document.querySelector("#statistics input[type=button]").addEventListener("click", initStatistics);
}

document.addEventListener("DOMContentLoaded", async function () {
    init();
});