import chart from 'chart.js'

class NtpGraph extends HTMLElement {
    constructor() {
        super();

        let ip = this.getAttribute("data-server-ip");

        this.innerHTML = `
            <span class="ntpBanner">${ip}</span>
            <span class="ntpContent">
                <a target="_blank" href="https://www.ntppool.org/scores/${ip}" class="linkToNtpPool">Server auf dem NTP Pool anzeigen</a>
                <canvas class="graphDelay"></canvas>
                <canvas class="graphScore"></canvas>
            </span>
        `;

        this.querySelector(".ntpBanner").onclick = () => {
            let contentElement = this.querySelector(".ntpContent");

            if (contentElement.classList.contains("visible")) {
                contentElement.classList.remove("visible");
            } else {
                contentElement.classList.add("visible");
            }

            let xhr = new XMLHttpRequest();

            xhr.onreadystatechange = () => {
                if (xhr.status === 200 && xhr.readyState === 4) {
                    let rawData = JSON.parse(xhr.responseText);
                    let x = [];
                    let yScore = [];
                    let yDelay = [];
                    rawData["history"].forEach((entry, index) => {
                        let date = new Date(entry["ts"] * 1000).toLocaleDateString();
                        if (index % 10 !== 0) {
                            date = "";
                        }
                        x.push(date);
                        yScore.push(entry["score"]);
                        yDelay.push(entry["offset"]);
                    });

                    this.drawPlot(".graphDelay", x, yDelay, "Delay");
                    this.drawPlot(".graphScore", x, yScore, "Score");


                }
            }
            xhr.open("GET", "https://www.ntppool.org/scores/" + ip + "/json?monitor=*&limit=800");
            xhr.send();

        }
    }

    drawPlot(elementName, x, y, title) {
        let ctx = this.querySelector(elementName).getContext('2d');

        new Chart(ctx, {
            type: 'line',
            responsive: true,
            scaleShowVerticalLines: false,
            showTooltips: false,
            data: {
                labels: x,
                datasets: [{
                    label: title,
                    data: y,
                    borderColor: '#199a87',
                    fill: false,
                    radius: 0,
                }]
            },
        });
    }

}

customElements.define("jl-ntp-graph", NtpGraph);