/*!
 * ChartJs Plugin
 * Chart.js v4.4.2
 * https://www.chartjs.org
 * (c) 2024 Chart.js Contributors Released under the MIT License
 * Thorium Builder, Copyright 2018-2024 Thorium builder, All Rights Reserved.
 */


var chartJS = {
    name: "ChartJs Plugin",
    bundleid: "com.thoriumbuilder.chartjs",
    version: "4.0",
    options: {
        responsive: true,
        aspectRatio: 1,
        maintainAspectRatio: true,
        scales: {
            x: {
                grid: {
                    display:true,
                    color: "rgba(128,128,128,0.3)",
                    lineWidth: 1,
                    tickColor: "rgba(128,128,128,0.2)",
                },
                ticks: {
                  display: true,
                }
              },
              y: {
                beginAtZero: false,
                grid:{
                    display:true,
                    color: "rgba(128,128,128,0.3)",
                    lineWidth: 1,
                    tickColor: "rgba(128,128,128,0.2)",
                }
              }    
        },
        layout: {
            padding :10,
        },

        plugins: {
            title: {
                align: "center",
                color: '#0000',
                display: false,
                fullSize: true,
                position: "top",
                font : {weight: 'bold'},
                padding: 10,
                text: "",
            },
            subtitle: {
                display: false,
                text: ''
            },
    
            legend: {
                display: true,
                position: "top",
                align: "center",
                maxHeight: 50,
                maxWidth: 300,
                title: "sfgfgdf",
                fullSize: true,               
                labels: {
                    color: "black",
                },
            },
           
            tooltip: {
                enabled : true,
            },
        }
    },
    initialize: function () {
        var x = document.querySelectorAll(".chartjs");
        for (var i = 0; i < x.length; i++) {
            var elt = x[i];
            var c = $(elt).data('chartinstance');
            if (!c) {
                thoriumapi.logEvent(0, "[com.thoriumbuilder.chartjs] Initializing Chart " + elt.id);
                var type = elt.getAttribute("data-plugin-type") || "line"; //line || bar || radar ||pie || doughnut || polarArea || bubble || scatter
                var labelsString = elt.getAttribute("data-plugin-dataset-labels") || "";
                var dataString = elt.getAttribute("data-plugin-dataset-data") || "";
                var colorString = elt.getAttribute("data-plugin-dataset-colors") || "";
                var mainTitle = elt.getAttribute("data-plugin-title-text") || "";
                var titleFontSize = elt.getAttribute("data-plugin-title-fontsize") || 17;
                var titleDisplay = elt.getAttribute("data-plugin-title-displayed") == "true" || false;
                var titlePosition = elt.getAttribute("data-plugin-title-position") || "bottom";
                var dataSetFill = elt.getAttribute("data-plugin-fill") == "true" || false;
                var dataLabel = elt.getAttribute("data-plugin-data-label") || "data";
                var showlines = elt.getAttribute("data-plugin-showlines") == "true" || false;
                var borderWidth = elt.getAttribute("data-plugin-border-width") || 2;
                var legendFontSize = elt.getAttribute("data-plugin-legend-fontsize") || 14;
                var legendfullWidth = elt.getAttribute("data-plugin-legend-fullwidth") == "true" || false;
                var legendDisplayed = elt.getAttribute("data-plugin-legend-displayed") == "true" || false;
                var legendPosition = elt.getAttribute("data-plugin-legend-position") || "bottom";
                var legendFontColor = elt.getAttribute("data-plugin-legend-fontcolor") || "gray";

                var responsive = elt.getAttribute("data-plugin-responsive") == "true" || false;
                var aspectRatio = elt.getAttribute("data-plugin-aspectratio") || 2;
                var maintainAspectRatio = elt.getAttribute("data-plugin-maintain-aspect-ratio")  == "true" || false;

                //Global Options
                chartJS.options.responsive= responsive;
                chartJS.options.aspectRatio=aspectRatio;
                chartJS.options.maintainAspectRatio=maintainAspectRatio;

                //Options Title
                chartJS.options.plugins.title.fontSize = titleFontSize;
                chartJS.options.plugins.title.display = titleDisplay;
                chartJS.options.plugins.title.text = mainTitle;
                chartJS.options.plugins.title.position = titlePosition;
                //Options Legend
                chartJS.options.plugins.legend.fontSize = legendFontSize;
                chartJS.options.plugins.legend.fullWidth = legendfullWidth;
                chartJS.options.plugins.legend.display = legendDisplayed;
                chartJS.options.plugins.legend.position = legendPosition,
                chartJS.options.plugins.legend.labels.fontColor = legendFontColor;
                //Data
                var labelsAray = labelsString.split('|');
                var dataArray = dataString.split('|');
                var bgColorsArray = colorString.split('|');
                var data = {
                    labels: labelsAray,
                    datasets: [{
                        label: dataLabel,
                        fill: dataSetFill,
                        borderColor: "rgba(0,200,150,0.9)",
                        borderWidth: borderWidth,
                        showLine: showlines,
                        data: dataArray,
                        backgroundColor: bgColorsArray,
                        borderColor: bgColorsArray,
                        tension: 0.4,
                    }]
                };

                elt.getContext('2d');
                var myChart = new Chart(elt, {
                    type: type,
                    data: data,
                    options: chartJS.options,
                })
                $(elt).data('chartinstance', myChart);
            }
        }
    },

    addDataSet: function (id, dataString, colorString, dataLabel) {
        var chart = chartJS.getChartInstanceFromId(id);
        if (chart) {
            var ctx = document.getElementById(id);
            ctx.getContext('2d');
            var dataArray = dataString.split('|');
            var bgColorsArray = colorString.split('|');
            var ds = {
                label: dataLabel,
                fill: false,
                borderColor: "rgba(0,200,150,0.9)",
                borderWidth: 5,
                showLine: true,
                data: dataArray,
                backgroundColor: bgColorsArray,
                borderColor: bgColorsArray,
                borderWidth: 1
            };
            var myDataset = chart.data.datasets;
            myDataset.push(ds);
            chart.update();
        }
    },

    getChartInstanceFromId: function (id) {
        var o = $("#" + id);
        if (!o) {
            thoriumapi.logEvent(1, "[com.thoriumbuilder.chartjs] Object with id [" + id + "] is not a Chart Instance");
            return null;
        }
        var chart = o.data('chartinstance');
        if (!chart) {
            thoriumapi.logEvent(1, "[com.thoriumbuilder.chartjs] Object with id [" + id + "] is not a Chart Instance");
            return null;
        }
        return chart;
    },

    addDataPoint: function (id, dataSet, label, value, color) {
        var chart = chartJS.getChartInstanceFromId(id);
        if (chart) {
            var myDataset = chart.data.datasets;
            if (!myDataset) {
                thoriumapi.logEvent(1, "[com.thoriumbuilder.chartjs] Object with id [" + id + "] does not have Dataset");
                return;
            }
            var i = myDataset[dataSet].data.length;
            if ((i == 1) && (chart.data.datasets[dataSet].data[0] == "")) { i = 0; }
            chart.data.labels[i] = label;
            chart.data.datasets[dataSet].data[i] = value;
            chart.data.datasets[dataSet].backgroundColor[i] = color;
            chart.update();
        }
    },

    replaceDataPoint: function (id, dataSet, index, label, value, color) {
        var chart = chartJS.getChartInstanceFromId(id);
        if (chart) {
            var myDataset = chart.data.datasets;
            if (index > myDataset[dataSet].data.length) {
                thoriumapi.logEvent(1, "[com.thoriumbuilder.chartjs] Invalid Index [" + index + "]");
                return;
            }
            chart.data.labels[index] = label;
            chart.data.datasets[dataSet].data[index] = value;
            chart.data.datasets[dataSet].backgroundColor[index] = color;
            chart.update();
        }
    },

    clearChart: function (id) {
        var chart = chartJS.getChartInstanceFromId(id);
        if (chart) {
            var elt=document.getElementById(id);
            $(elt).data('chartinstance', null);
            chart.destroy();
        }
    },

    changeChartType(id,newType) {
        var myDataset;
        var elt=document.getElementById(id);
        elt.setAttribute("data-plugin-type",newType);
        var chart = chartJS.getChartInstanceFromId(id);
        if (chart) {
            $(elt).data('chartinstance', null);
            myData = chart.data;
            myOption= chartJS.options;
            chart.destroy();
        }

        var myChart = new Chart(elt, {
            scaleFontColor: "#FFFFFF",
            type: newType,
            data: myData,
            options: myOption,
        })
        $(elt).data('chartinstance', myChart);
    }
}

$(document).on('page:beforein', function (e) {
    var page = e.detail;
    chartJS.initialize();
})

/*-- Initialize -- */
document.addEventListener('appLoaded', function (e) {
	chartJS.initialize();		
}, false);