var data = [];
var lineChart;
showHide(true);

function moreData() {

    util.getAnalyticsdata((analytics) => {

        //var info = JSON.parse(analytics);

        //alert(analytics);

        var info = analytics;

        var ctx = document.getElementById("pieChart");
        var pieChart = new Chart(ctx, {
            type: 'pie',
            data: {
                labels: info.labels,
                datasets: [{
                    data: info.data,
                    backgroundColor: ['#007bff', '#dc3545', '#ffc107', '#28a745'],
                }],
            },
        });

        util.getMonthlyInstalls((dashboardData) => {

            showHide(false);

            //dashboardData = JSON.parse(dashboardData);
            data = dashboardData;
            var lineGraphData = dashboardData.line;

            $('#activeInstallations').html(data.activeinstalls);

            var ctx = document.getElementById('canvas').getContext('2d');
            lineChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: lineGraphData.labels,
                    datasets: [{
                        label: "Monthly Installations",
                        backgroundColor: 'rgb(255, 212, 221)',
                        pointRadius: 5,
                        pointHitRadius: 50,
                        borderColor: 'rgb(255, 99, 132)',
                        data: lineGraphData.data,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    title: {
                        display: false,
                        text: 'Chart.js Line Chart'
                    },
                    tooltips: {
                        mode: 'index',
                        intersect: false,
                    },
                    hover: {
                        mode: 'nearest',
                        intersect: true
                    },
                    scales: {
                        xAxes: [{
                            display: true,
                            scaleLabel: {
                                display: true,
                                labelString: 'Monthly Installations'
                            }
                        }],
                        yAxes: [{
                            display: true,
                            scaleLabel: {
                                display: true,
                                labelString: 'Devices'
                            }
                        }]
                    },
                    legend: {
                        display: false
                    },
                }
            });

            var doc = document.getElementById("horizontalBar");
            var horizontalBar = new Chart(doc, {
                type: 'horizontalBar',
                data: {
                    labels: data.bar.labels,
                    datasets: [{
                        label: "Installations",
                        backgroundColor: "rgba(2,117,216,1)",
                        borderColor: "rgba(2,117,216,1)",
                        data: data.bar.data,
                    }],
                },
                options: {
                    scales: {
                        xAxes: [{
                            time: {
                                unit: 'month'
                            },
                            gridLines: {
                                display: false
                            },
                            ticks: {
                                beginAtZero: true
                                // maxTicksLimit: 9
                            },
                            display: true,
                            scaleLabel: {
                                display: true,
                                labelString: 'Devices'
                            }
                        }],
                        yAxes: [{
                            ticks: {
                                min: 0,
                                max: 1000,
                                maxTicksLimit: 8
                            },
                            gridLines: {
                                display: true
                            },
                            display: true,
                            scaleLabel: {
                                display: true,
                                labelString: 'Monthly Installations'
                            },
                            stacked: true
                        }],
                    },
                    legend: {
                        display: false
                    }
                }
            });


            var ctx = document.getElementById("verticalBar");
            var vLineChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: data.btmBar.labels,
                    datasets: [{
                        label: "Past 7 days Installs",
                        backgroundColor: "rgba(2,117,216,1)",
                        borderColor: "rgba(2,117,216,1)",
                        data: data.btmBar.data,
                    }],
                },
                options: {
                    scales: {
                        xAxes: [{
                            time: {
                                unit: 'month'
                            },
                            gridLines: {
                                display: false
                            },
                            display: true,
                            scaleLabel: {
                                display: true,
                                labelString: 'Past 7 days Installations'
                            },
                            ticks: {
                                maxTicksLimit: 9
                            }
                        }],
                        yAxes: [{
                            ticks: {
                                min: 0,
                                // max: 100,
                                maxTicksLimit: 8
                            },
                            gridLines: {
                                display: true
                            },
                            scaleLabel: {
                                display: true,
                                labelString: 'Devices'
                            }
                        }],
                    },
                    legend: {
                        display: false
                    }
                }
            });

            //dotnut
            var total = data.pie.data.reduce((a, v) => a + v);
            var inPercent = data.pie.data.map(v => Math.max(v / total * 100, 1));

            var config = {
                type: 'doughnut',
                data: {
                    datasets: [{
                        data: inPercent,
                        backgroundColor: [
                            '#28a745',
                            '#e83e8c',
                            '#ffd4dd',
                            '#007bff'
                        ],
                        label: 'Dataset 1'
                    }],
                    labels: data.pie.labels,
                },
                options: {
                    responsive: true,
                    legend: {
                        position: 'top',
                    },
                    title: {
                        display: false,
                    },
                    animation: {
                        animateScale: true,
                        animateRotate: true
                    },
                    tooltips: {
                        enabled: true,
                        mode: 'nearest',
                        callbacks: {
                            label: function (tooltipItem) {
                                var value = data.pie.data[tooltipItem.index];
                                var label = data.pie.labels[tooltipItem.index];
                                return `${label}: ${value}`;
                            }
                        }
                    }
                }
            };

            var ctx = document.getElementById('chart-area').getContext('2d');
            var dotnutChart = new Chart(ctx, config);

        });
    });
}

function getUrlParameter() {
    var url = window.location.href.split('/');
    var page = url[url.length - 1];
    return page.split(".")[0];
}

function bootstrapTable(data, label) {

    $('#table').bootstrapTable({
        data: data,
        formatLoadingMessage: function () {
            return '';
            // '<b> InstbootstrapTableallations (' + data.length + ')</b>';
        }
    });

    $('#classModal').modal('show');
    $('#title').html(label + ' Installations (' + data.length + ')');
};

function showHide(flag) {

    if (flag) {
        $(".row").hide();
        $(".small").show();
    }
    else {
        $(".row").show();
    }
}

$(document).ready(function () {

    var user = sessionStorage.getItem('user');
    if (user == null || user == undefined) {
        window.location = "index.html";
        // return;  
    }
    
    util.getTodaysInformation((data) => {

        //data = JSON.parse(data);
        $('#overSpeed').html(data.overSpeed);
        $('#startEvents').html(data.startEvents);
        $('#stopEvents').html(data.stopEvents);
        $('#todaytrips').html(data.todaytrips);
        $('#deactivate').html(data.deactivate);

        moreData();
    });

    /*
    var currentpage = getUrlParameter();
    if (currentpage != "login") {
        if (window.sessionStorage) {
            var user = sessionStorage.getItem('user');
            if (user == null || user == undefined) {
                window.location = "index.html";
                // return;  
            }
        }
    }*/

    const data = JSON.parse(sessionStorage.getItem('user'));
    $("#name").html(data.name);
    $("#surname").html(data.surname);

});

$("#canvas").click(
    function (evt) {
        var activePoints = lineChart.getElementsAtEvent(evt);
        if (activePoints.length) {
            var firstPoint = activePoints[0];
            var label = lineChart.data.labels[firstPoint._index];
            // var value = lineChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];

            util.getMonthInstalls(label, (data) => {
                //bootstrapTable(JSON.parse(data), label);
                bootstrapTable(data, label);
            });
        }
});

$('#classModal').on('hidden.bs.modal', function (e) {
    $('#table').bootstrapTable("destroy");
});








