// $(window).on('load', function () {
window.addEventListener("load", (event) => {

    /**
     * This piece of code is used to draw the total value of a doughnut
     * in the center of itself. The value is automatically calculated
     * using the data defined in the doughnut.
     *
     *  @param {object} chart - The chartjs object
     *  @param {string} label - The label that is shown below the number.
     *  @param {number} completionRate
     *
     *  @return void
     */
    function drawDoughnutNumber(chart, label, completionRate) {
        if (!completionRate) {
            completionRate = 1;
        }
        var width = chart.width,
            height = chart.height,
            ctx = chart.ctx;


        ctx.restore();
        var fontSize = (height / 100).toFixed(2);

        ctx.fillStyle = '#333';
        ctx.textBaseline = "middle";
        ctx.font = "bold " + fontSize + "em sans-serif";

        // Draw the number
        var value = chart.data.datasets[0].data.reduce(function (x, y) {
            return x + y;
        }, 0);
        var valueX = Math.round((width - ctx.measureText(value).width) / 2);
        var valueY = height / 2 + (fontSize * 2);

        ctx.fillText(Math.round(value * completionRate), valueX, valueY);

        // Draw the label
        ctx.fillStyle = '#666';
        fontSize = (height / 350).toFixed(2);
        ctx.font = fontSize + "em sans-serif";
        var textX = Math.round((width - ctx.measureText(label).width) / 2);
        var textY = height / 2 - (fontSize * 25);
        ctx.fillText(label, textX, textY);

        ctx.save();
    }
    Chart.defaults.animationSteps = 60;
    Chart.defaults.responsive = true;
    Chart.defaults.maintainAspectRatio = true;
    Chart.defaults.responsiveAnimationDuration = 1000;

    // Only render the charts if they are inside of the viewport
    // this improves the performance, especially on mobile devices.
    //$('.ig-chart').one('inview', function (event, visible) {
    let chartElements = document.getElementsByClassName('ig-chart');
    for (let index = 0; index < chartElements.length; index++) {
        let inview = InView(chartElements[index], function (visible) {
            if (visible && !chartElements[index].classList.contains('loaded')) {
                let element = chartElements[index];

                var ctx = element,
                    chartType = element.dataset.charttype,
                    showLegend = element.dataset.showlegend,
                    yScaleSuffix = element.dataset.yscalesuffix,
                    xScaleSuffix = element.dataset.xscalesuffix,
                    data = JSON.parse(element.dataset.chart);

                var chartSettings = {
                    // Doughnut specific options
                    cutoutPercentage: element.dataset.cutoutpercentage,
                    showDoughnutTotal: element.dataset.showdoughnuttotal,
                    doughnutTotalSuffix: element.dataset.doughnuttotalsuffix,

                    // Scale options
                    showXScale: element.dataset.showxscale,
                    showYScale: element.dataset.showyscale,
                    yStepSize: element.dataset.ystepsize,
                    yScaleMax: element.dataset.yscalemax,
                    yScaleMin: element.dataset.yscalemin,
                    xStepSize: element.dataset.xstepsize,
                    xScaleMax: element.dataset.xscalemax,
                    xScaleMin: element.dataset.xscalemin,
                    xReverse: element.dataset.xreverse,
                    yReverse: element.dataset.yreverse,
                    xScalePosition: element.dataset.xscaleposition,
                    yScalePosition: element.dataset.yscaleposition,
                    scaleFontFamily: element.dataset.scalefontfamily,
                    scaleFontColor: element.dataset.scalefontcolor,
                    scaleFontSize: element.dataset.scalefontsize,
                    scaleFontStyle: element.dataset.scalefontstyle,

                    // Global options
                    animationDuration: element.dataset.animationduration,
                    animationEasing: element.dataset.animationeasing,
                    animationDelay: element.dataset.animationdelay
                };

                var additionalOptions = element.dataset.additionalOptions;
                // Setting duration for the chart animations. This setting can
                // only be applied globally for now.
                Chart.defaults.animation.duration = chartSettings.animationDuration;
                Chart.defaults.animation.easing = chartSettings.animationEasing;

                Chart.defaults.animation.onComplete = function (a) {
                    delayed = chartSettings.animationDelay > 0;
                    a.chart.initialAnimationIsComplete = true;
                };
                if (chartSettings.animationDelay > 0) {
                    Chart.defaults.animation.delay = function (context) {
                        return 200;
                    };
                }
                // console.log(chartSettings);
                Chart.defaults.animation.onProgress = function (a) {
                    if (!a.chart.initialAnimationIsComplete) {
                        // Code for counting up the doughnut total
                        if (a.chart.config.type == 'doughnut' && chartSettings.showDoughnutTotal) {
                            var completionRate = a.currentStep / a.numSteps;
                            drawDoughnutNumber(a.chart, chartSettings.doughnutTotalSuffix, completionRate);
                        }
                    } else {
                        if (a.chart.config.type == 'doughnut' && chartSettings.showDoughnutTotal) {
                            drawDoughnutNumber(a.chart, chartSettings.doughnutTotalSuffix, 1);
                        }
                    }
                };

                // Set default values for some of the options
                if (!chartSettings.xStepSize) {
                    chartSettings.xScaleMax = undefined
                }

                if (!chartSettings.xScaleMax) {
                    chartSettings.xScaleMax = undefined
                }

                if (!chartSettings.xScaleMin) {
                    chartSettings.xScaleMin = 0
                }

                if (!chartSettings.yStepSize) {
                    chartSettings.yScaleMax = undefined
                }

                if (!chartSettings.yScaleMax) {
                    chartSettings.yScaleMax = undefined
                }

                if (!chartSettings.yScaleMin) {
                    chartSettings.yScaleMin = 0
                }

                var options = {
                    plugins: {}
                };

                if (chartType == 'bar' || chartType == 'horizontalBar') {
                    options = {
                        hover: {
                            mode: "single"
                        },
                        tooltip: {
                            enabled: true,
                            callbacks: {
                                label: function (context) {
                                    // Depending on the bar type return the correct label
                                    if (chartType == 'bar') {
                                        return context.dataset.label + ': ' + context.parsed.y + yScaleSuffix;
                                    } else {
                                        return context.dataset.label + ': ' + context.parsed.x + xScaleSuffix;
                                    }
                                }
                            }
                        },
                        scales: {
                            x: {
                                display: chartSettings.showXScale,
                                position: chartSettings.xScalePosition,
                                reverse: chartSettings.xReverse,
                                ticks: {
                                    fontFamily: chartSettings.scaleFontFamily,
                                    fontColor: chartSettings.scaleFontColor,
                                    fontSize: chartSettings.scaleFontSize,
                                    fontStyle: chartSettings.scaleFontStyle,
                                    max: chartSettings.xScaleMax,
                                    min: chartSettings.xScaleMin,
                                    stepSize: chartSettings.xStepSize,
                                    autoSkip: false,
                                    // Adding the suffix the scale label.
                                    callback: function (value, index, values) {
                                        return '' + this.getLabelForValue(value) + xScaleSuffix;
                                    }
                                }
                            },
                            y: {
                                display: chartSettings.showYScale,
                                position: chartSettings.yScalePosition,
                                reverse: chartSettings.yReverse,
                                ticks: {
                                    fontFamily: chartSettings.scaleFontFamily,
                                    fontColor: chartSettings.scaleFontColor,
                                    fontSize: chartSettings.scaleFontSize,
                                    fontStyle: chartSettings.scaleFontStyle,
                                    max: chartSettings.yScaleMax,
                                    min: chartSettings.yScaleMin,
                                    stepSize: chartSettings.yStepSize,
                                    // Adding the suffix the scale label.
                                    callback: function (value, index, values) {
                                        return '' + this.getLabelForValue(value) + xScaleSuffix;
                                    }
                                }
                            }
                        },
                        plugins: {}
                    }
                    if (chartType == 'horizontalBar') {
                        chartType = 'bar';
                        options.indexAxis = 'y';
                    }
                }

                if (chartType == 'line') {
                    options = {
                        fill: false,
                        hover: {
                            mode: "single"
                        },
                        plugins: {
                            tooltip: {
                                enabled: true,
                                callbacks: {
                                    label: function (context) {
                                        return context.dataset.label + ': ' + context.parsed.y + yScaleSuffix;
                                    }
                                }
                            }
                        },
                        scales: {
                            x: {
                                display: chartSettings.showXScale,
                                position: chartSettings.xScalePosition,
                                reverse: chartSettings.xReverse,
                                ticks: {
                                    fontFamily: chartSettings.scaleFontFamily,
                                    fontColor: chartSettings.scaleFontColor,
                                    fontSize: chartSettings.scaleFontSize,
                                    fontStyle: chartSettings.scaleFontStyle,
                                    max: chartSettings.xScaleMax,
                                    min: chartSettings.xScaleMin,
                                    stepSize: chartSettings.xStepSize,
                                    // Adding the suffix the scale label.
                                    callback: function (value, index, values) {
                                        return '' + this.getLabelForValue(value) + xScaleSuffix;
                                    }
                                }
                            },
                            y: {
                                display: chartSettings.showYScale,
                                position: chartSettings.yScalePosition,
                                reverse: chartSettings.yReverse,
                                ticks: {
                                    fontFamily: chartSettings.scaleFontFamily,
                                    fontColor: chartSettings.scaleFontColor,
                                    fontSize: chartSettings.scaleFontSize,
                                    fontStyle: chartSettings.scaleFontStyle,
                                    max: chartSettings.yScaleMax,
                                    min: chartSettings.yScaleMin,
                                    stepSize: chartSettings.yStepSize,
                                    // Adding the suffix the scale label.
                                    callback: function (value, index, values) {
                                        return '' + value + yScaleSuffix;
                                    }
                                }
                            }
                        },
                        plugins: {}
                    };
                }

                if (chartType == 'radar') {
                    options = {
                        plugins: {}
                    };
                }

                // Legend settings for each chart type.

                options.plugins.legend = {
                    display: showLegend,
                    position: 'bottom'
                };

                // Pie and doughnut charts are essentially the same type of
                // chart. So the same settings should be applied to both of them.
                if (chartType == 'pie' || chartType == 'doughnut') {
                    options = {

                        // We use a custom legend for pie charts, so we disable
                        // the default one. Because this way we can have more control
                        // over the legend.
                        plugins: {
                            legend: {
                                display: false
                            },
                        }
                    };
                }

                if (chartType == 'doughnut') {
                    options.cutoutPercentage = chartSettings.cutoutPercentage;
                }

                options.initialAnimationIsComplete = false;

                if (typeof additionalOptions != 'undefined') {
                    Object.assign(options, additionalOptions);
                }
                // Creating the actual chart object.
                let chart = new Chart(ctx, {
                    type: chartType,
                    data: data,
                    options: options
                });


                // We generate and show a custom legend for pie and doughnut
                // charts, if needed.
                if (showLegend && (chartType == "pie" || chartType == "doughnut")) {
                    let list = document.createElement('ul');
                    let data = chart.data;
                    let datasets = data.datasets;
                    let labels = data.labels;

                    list.setAttribute('class', chart.id + '-legend chart-legend ' + chartType + '-legend');
                    let items = chart.options.plugins.legend.labels.generateLabels(chart);
                    for (let index = 0; index < items.length; index++) {
                        let item = items[index];
                        let listItem = document.createElement('li');
                        let listItemSpan = listItem.appendChild(document.createElement('span'));
                        listItemSpan.style.backgroundColor = datasets[0].backgroundColor[index];
                        if (labels[index]) {
                            listItem.appendChild(document.createTextNode(labels[index]));
                        }
                        listItem.onclick = () => {
                            chart.toggleDataVisibility(item.index);
                            chart.update();
                        };
                        list.appendChild(listItem);
                    }
                    element.parentNode.after(list);
                }
                element.classList.add('loaded');
            }
        });
    }
});
