const getRequestBody = (items) => {
    return {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(items),
    };
};

new Vue({
    el: "#app",
    data() {
        return {
            allRemotesStats: true,
            remotes: [],
            selectedRemotes: [],
            remoteStats: {},
            remoteAllStats: {},
        };
    },
    created() {
        this.getRemotes();
        this.getRemoteAllStats();
    },
    methods: {
        changeStatsType(value) {
            this.allRemotesStats = value;
        },
        async getRemotes() {
            const res = await fetch("http://localhost:3000/api/remotes");
            const finalRes = await res.json();
            this.remotes = finalRes;
        },
        async getRemoteAllStats() {
            const res = await fetch("http://localhost:3000/api/remotes/stats");
            const finalRes = await res.json();
            this.remoteAllStats = finalRes.stats;
        },
        remoteSelected(event) {
            this.getRemoteStats();
        },
        async getRemoteStats() {
            const res = await fetch("http://localhost:3000/api/remotes/stats", getRequestBody({ remote: this.selectedRemotes }));
            const finalRes = await res.json();
            this.remoteStats = finalRes;
            this.genVersionsChart();
        },
        genVersionsChart() {
            const ctx = document.getElementById("versions").getContext("2d");
            var myChart = new Chart(ctx, {
                type: "line",
                data: {
                    labels: this.remoteStats.versions.map((v) => `${v.version} - ${v.date}`),
                    datasets: [
                        {
                            data: this.remoteStats.versions.map((v) => v.duration),
                            label: "Duration",
                            borderColor: "#3e95cd",
                            backgroundColor: "#7bb6dd",
                            fill: false,
                        },
                    ],
                },
            });
        },
    },
});
