(function ($) {
    "use strict";
  
    var ElementorChartWidget = function ($scope, $) {

        var chartElements = $scope.find('.htmega-doughunt-chartjs').eq(0);

        var charData = JSON.parse(chartElements[0].dataset.htmegachart);
        var chartDataSettings = JSON.parse(chartElements[0].dataset.chart_settings);


        const charData2 = charData.map(gradientColor => ({
            ...gradientColor,
            itemStyle: { 
                color: new echarts.graphic.LinearGradient( 10, 0, 10, 1,  gradientColor.itemStyle.color)
            }
        }))

        var chartType = chartDataSettings.chart_type;
        var roseTypeRadius = '';
        var chartRadius = ['0%', '70%'];
        var borderWidth = (chartDataSettings.chart_border_width)?chartDataSettings.chart_border_width:0;
        var borderColor = (chartDataSettings.chart_border_color)?chartDataSettings.chart_border_color:'#ffffff';
        var borderRadius = (chartDataSettings.chart_border_radius)?chartDataSettings.chart_border_radius:0;
        var chart_hover_value_center = (chartDataSettings.chart_hover_value_center)?chartDataSettings.chart_hover_value_center:false;

        var legend_color = (chartDataSettings.legend_color)?chartDataSettings.legend_color:'#000000';
        var legend_size = (chartDataSettings.legend_size)?chartDataSettings.legend_size:'20';
        var show_y_axis_label = (chartDataSettings.show_y_axis_label == 'true') ? true: false;

        var barxAxis = 'xAxis';
        var baryAxis = 'yAxis';
        if( 'doughnut' == chartType ){
            var chart_inner_radius = (chartDataSettings.chart_inner_radius)?chartDataSettings.chart_inner_radius:30;
            var chart_outer_radius = (chartDataSettings.chart_outer_radius)?chartDataSettings.chart_outer_radius:70;

            chartRadius = [chart_inner_radius+'%', chart_outer_radius+'%'];
        } else if('doughnut_round' == chartType){
            var chart_inner_radius = (chartDataSettings.chart_inner_radius)?chartDataSettings.chart_inner_radius:54;
            var chart_outer_radius = (chartDataSettings.chart_outer_radius)?chartDataSettings.chart_outer_radius:86;

            borderWidth = (chartDataSettings.chart_border_width)?chartDataSettings.chart_border_width:2;
            chartRadius = [chart_inner_radius+'%', chart_outer_radius+'%'];
        } else if('pie' == chartType){
            var chart_outer_radius = (chartDataSettings.chart_outer_radius)?chartDataSettings.chart_outer_radius:70;
            chartRadius = ['0%', chart_outer_radius+'%'];
        } else if('nightingale_chart' == chartType){
            var chart_inner_radius = (chartDataSettings.chart_inner_radius)?chartDataSettings.chart_inner_radius:54;
            var chart_outer_radius = (chartDataSettings.chart_outer_radius)?chartDataSettings.chart_outer_radius:85;
            chartRadius = [chart_inner_radius+'%', chart_outer_radius+'%'];
            var roseTypeRadius = 'radius';
        } else if('bar_h' == chartType){
            barxAxis = 'yAxis';
            baryAxis = 'xAxis';
        }

         //tablet and mobile devices controll
        var currentDevice = elementorFrontend.getCurrentDeviceMode();
        var chart_legend_position = 'top';
        var chartLegendShow = true;
        var legendGap = 20;
        if('tablet' == currentDevice ){
            chart_legend_position = chartDataSettings.chart_legend_positiont;
            chartLegendShow = chartDataSettings.chart_legend_showt;
            legendGap = chartDataSettings.legend_gapt;
        } else if('mobile' == currentDevice  ){
            chart_legend_position = chartDataSettings.chart_legend_positionm;
            chartLegendShow = chartDataSettings.chart_legend_showm;
            legendGap = chartDataSettings.legend_gapm;
        } else {
            chart_legend_position = chartDataSettings.chart_legend_position;
            chartLegendShow = chartDataSettings.chart_legend_show;
            legendGap = chartDataSettings.legend_gap;
        }

        var chart_orient = 'horizontal';
        var legendVarAlign = 'top';
        if( 'left' == chart_legend_position || 'right' == chart_legend_position ){
            chart_orient = 'vertical';
            legendVarAlign = 'center';
        } else if('bottom' == chart_legend_position){
            legendVarAlign = 'bottom';
        }

        if ( chartElements.length > 0 ) {
            var settings = chartElements.data('settings');
            
            var chartElementsMyChart = echarts.init(chartElements[0], null, {
                renderer: 'canvas',
                useDirtyRect: false
            });
            var htmegaBarOption;
            if( chartType == 'bar' || chartType == 'bar_h'){

                const barLegendColor = charData.map(({ itemStyle }) => itemStyle);
                barLegendColor.map(function(cValue, cIndex, cArray){
                    return cArray[cIndex] =  new echarts.graphic.LinearGradient( 10, 0, 10, 1,cValue.color);
                });

                // Bar Chart data generate
                const barChartData =  charData.map(function(currentValue, index, arr){        
                    return arr[index] = 
                    {'name':currentValue.name,
                        type:'bar',
                        emphasis: { focus: 'series'},
                        data: currentValue.value.map(function(currentValue2, index2, arr2){
                            
                            return arr2[index2] = {value: currentValue2, itemStyle:{ color:new echarts.graphic.LinearGradient( 10, 0, 10, 1,[{offset:0,color:currentValue.itemStyle.color[0].color},{offset:1,color:currentValue.itemStyle.color[1].color}]) }}
                          })
                    }

                });

                const barLegends = barChartData.map(({ name }) => name);
                htmegaBarOption = {
                    color: barLegendColor,
                    tooltip: {
                        show: chartDataSettings.chart_tool_tips,
                        trigger: 'axis',
                        borderColor: chartDataSettings.tooltip_bg_color,
                        backgroundColor: chartDataSettings.tooltip_bg_color,
                        textStyle:{
                            color:chartDataSettings.tooltip_color,  
                        },
                        axisPointer: {
                            type: 'shadow',
                            stroke: "#000000"
                        }
                    },
                    legend: {
                        show: chartLegendShow,
                        orient: chart_orient, // 'horizontal'
                        [chart_legend_position]: '0',
                        itemGap: legendGap,
                        textStyle: { color: legend_color, fontSize: legend_size+'px' },
                        data: barLegends
                    },
                    grid: {
                        left: chartDataSettings.chart_outer_space.left+chartDataSettings.chart_outer_space.unit,
                        right: chartDataSettings.chart_outer_space.right+chartDataSettings.chart_outer_space.unit,
                        bottom: chartDataSettings.chart_outer_space.bottom+chartDataSettings.chart_outer_space.unit,
                        top: chartDataSettings.chart_outer_space.top+chartDataSettings.chart_outer_space.unit,
                        containLabel: true,
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                              type: 'shadow',
                              label: {
                                show: true,
                                bottom: '30',
                                borderColor:chartDataSettings.tooltip_bg_color,
                                backgroundColor:chartDataSettings.tooltip_bg_color,
                                color: chartDataSettings.tooltip_color,
                                formatter: function (params) {
                                  return params.value.replace('\n', '');
                                }
                              }
                            }
                        }
                    },
                    [barxAxis]: [
                        {
                            type: 'category',
                            axisTick: { show: false, alignWithLabel: false },
                            splitLine: { show: false },
                            axisLabel: {
                                width: 100, //fixed number of pixels
                                overflow: 'truncate', // or 'break' to continue in a new line
                                interval: 0,
                                rotate: 0, //If the label names are too long you can manage this by rotating the label.
                                color:chartDataSettings.axis_color,
                            },
                            data: chartDataSettings.bar_x_axis_labels
                        }
                    ],
                    [baryAxis]: [
                        {
                            show: show_y_axis_label,
                            type: 'value',
                            axisLabel: {
                                rotate: 0, //If the label names are too long you can manage this by rotating the label.
                                color:chartDataSettings.axis_color,
                            },
                        }
                    ],
                    series: barChartData
                };
                if (htmegaBarOption && typeof htmegaBarOption === 'object') {
                    chartElementsMyChart.setOption(htmegaBarOption);
                }

            } else if( chartType == 'line' ){
                // Line chart activation
                var htmegaSmoothedOption;

                htmegaSmoothedOption = {
                    tooltip: {
                        show: chartDataSettings.chart_tool_tips,
                        trigger: "item",
                        formatter: "${c}",
                        borderColor: chartDataSettings.tooltip_bg_color,
                        backgroundColor: chartDataSettings.tooltip_bg_color,
                        textStyle:{
                            color:chartDataSettings.tooltip_color,  
                        }
                    },
                    xAxis: [
                        {
                            type: "category",
                            axisTick: { show: false, alignWithLabel: false },
                            splitLine: {
                                show: true,
                                interval: "auto",
                                lineStyle: {
                                // Dark and light colors will be used in turns
                                color: ["rgba(115, 113, 255, 0.05"]
                                },
                                type: [5, 0],
                                dashOffset: 0
                            },
                            axisLabel: {
                                width: 0, //fixed number of pixels
                                overflow: "truncate", // or 'break' to continue in a new line
                                interval: 0
                            },
                            axisLine: {
                                show: false
                            }
                        }
                    ],
                    yAxis: [{ show:show_y_axis_label, type: "value",axisLabel: {
                            color:chartDataSettings.axis_color,
                    }, }],
                    legend: {
                        show: chartLegendShow,
                        orient: 'horizontal', // 'horizontal'
                        [chart_legend_position]: '0',
                        itemGap: legendGap,
                        textStyle: { color: legend_color, fontSize: legend_size+'px' },
                    },
                    grid: {
                        left: chartDataSettings.chart_outer_space.left+chartDataSettings.chart_outer_space.unit,
                        right: chartDataSettings.chart_outer_space.right+chartDataSettings.chart_outer_space.unit,
                        bottom: chartDataSettings.chart_outer_space.bottom+chartDataSettings.chart_outer_space.unit,
                        top: chartDataSettings.chart_outer_space.top+chartDataSettings.chart_outer_space.unit,
                    },
                    series: charData
                };
            
                if ( htmegaSmoothedOption && typeof htmegaSmoothedOption === "object" ) {
                    chartElementsMyChart.setOption(htmegaSmoothedOption);
                }

            } else {

                var htmegaDougOption;
                htmegaDougOption = {
                    tooltip: {
                        show: chartDataSettings.chart_tool_tips,
                        trigger: 'item',
                        borderColor: chartDataSettings.tooltip_bg_color,
                        borderWidth: '1',
                        padding: 5,
                        backgroundColor: chartDataSettings.tooltip_bg_color,
                        textStyle: {
                        color: chartDataSettings.tooltip_color,
                        fontSize: '',
                        fontFamily: '',
                        fontWeight: '',
                        }
                    },
                    toolbox: {
                        show: false,
                        feature: {
                        mark: { show: true },
                        dataView: { show: true, readOnly: true },
                        restore: { show: true },
                        saveAsImage: { show: true },
                        }
                    },
                    legend: {
                        show: chartLegendShow,
                        orient: chart_orient, // 'horizontal'
                        [chart_legend_position]: '0',
                        borderRadius: 0,
                        top: legendVarAlign,
                        backgroundColor: 'transparent',
                        borderColor: 'none',
                        borderWidth: 20,
                        padding: 10, // [5, 10, 15, 20]
                        itemGap: legendGap,
                        textStyle: { color: legend_color, fontSize: legend_size+'px' },
                        selected: {
                            Precipitation: false
                        }
                    },
                    series: [
                        {
                            name: chartDataSettings.chart_tool_title, 
                            type: 'pie',
                            center: ['50%', '50%'], 
                            //avoidLabelOverlap: true,
                            radius: chartRadius,
                            roseType: roseTypeRadius,
                            top:'0',
                            left:'0',
                            labelLine: {
                                show: false
                            },
                            itemStyle: {
                                borderRadius:borderRadius,
                                borderColor: borderColor,
                                borderWidth: borderWidth
                            },
                            label: {
                                show: false,
                                position: 'center',
                                formatter: '{d}%',
                                fontWeight: 'bold'
                            },
                            emphasis: {
                                label: {
                                    show: chart_hover_value_center,
                                    fontSize: chartDataSettings.hover_value_size,
                                    color: chartDataSettings.hover_value_color,
                                    fontWeight: 'bold'
                                }
                            },
                            data: charData2
                        }
                    ]
                };
            
                if (htmegaDougOption && typeof htmegaDougOption === 'object') {
                    chartElementsMyChart.setOption(htmegaDougOption);
                }   
            }

        }
    }

    // Run this code under Elementor.
    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction( 'frontend/element_ready/htmega-chart-addons.default', ElementorChartWidget);
    });      


})(jQuery);
