let chartManager = new ChartManager();

//#region MAIN FUNCTIONS
function set_chart() {

    if(chartManager.isModuleSet() == false) return;

    let chartCounter = 0;

    $('.LimitlessPieChart').each(function() {

        chartCounter++;
        let elementChart = $(this);
        elementChart.attr('id', 'LimitlessPieChart' + chartCounter);

        init_chart(elementChart[0].id);

    });

}
function init_chart(chartId) {

    // Define element
    let chartElement = document.getElementById(chartId);

    if (chartElement) {

        let elementObject = $(chartElement);
        let chartInstance = echarts.init(chartElement);

        chartInstance.showLoading(chartManager.defaultLoadingOptions);

        set_data(elementObject, function(options) {
            chartInstance.hideLoading();
            chartInstance.setOption(options);
            chartManager.setResizeEvent(chartElement, chartInstance);
        })
    }
}
function set_data(elementObject, callback) {

    setTimeout(function() {

        let options;

        let objectData = chartManager.getObjectData(elementObject);
        let rawData = chartManager.getRawData(objectData, elementObject);

        if(rawData == null) {

            // variables (this will be set by user)
            let title = objectData?.title ?? (elementObject.attr('title') ?? null);
            let subtitle = objectData?.subtitle ?? (elementObject.attr('subtitle') ?? null);
            let pieType = objectData?.pieType ?? (elementObject.attr('pie-type') ?? null); // donut or rose types
            let showLabel = objectData?.label ?? ((elementObject.attr('label') == 'true' || elementObject.attr('label') == true));
            let labelOnEmphasis = objectData?.labelOnEmphasis ?? ((elementObject.attr('emphasis-label') == 'true' || elementObject.attr('emphasis-label') == true));

            let series = chartManager.getChartSeries(objectData, elementObject);
            let nested = (Array.isArray(series) && series.length > 1) ?? false;

            if(Array.isArray(series) && series.length == 1) series = series[0]; // if series is array and has only one object then set first

            let seriesNames = setSeriesNames(series, nested);
            let seriesObject = nested ? setNestedSeries(series, showLabel, labelOnEmphasis) : setSeries(series, pieType, showLabel, labelOnEmphasis);

            // Options
            options = {

                // Chart title
                title: setTitle(title, subtitle),

                // Define colors
                color: chartManager.getColors(objectData, elementObject),

                // Global text styles
                textStyle: chartManager.defaultGlobalTextStyle,

                // Chart animation duration
                animationDuration: chartManager.getAnimationDuration(objectData, elementObject),

                // Add legend
                legend: setLegend(seriesNames),

                // Add tooltip
                tooltip: setTooltip(),

                // Add series
                series: seriesObject
            };

        } else {
            options = rawData;
        }

        callback(options);

    }, 1000);

}
//#endregion

//#region FUNCTIONS FOR OPTIONS
function setSeries(series, pieType, showLabel, labelOnEmphasis) {

    if(!series || series.length == 0) return [];

    let data = {
        name: series.name,
        type: 'pie',
        data: series.data,
        center: ['50%', '57.5%'],
        itemStyle: {
            normal: {
                borderWidth: 2,
                borderColor: '#353f53'
            }
        },
    }

    switch (pieType) {
        case "donut":
            data.radius = ['50%', '70%'];
            break;
        case "rose":
            data.radius = ['15%', '80%'];
            data.roseType = 'radius';
            break;
        default:
            data.radius = '70%';
            break;
    }

    data.itemStyle.normal.label = { show: showLabel };
    data.itemStyle.normal.labelLine = { show: showLabel };
    data.itemStyle.emphasis = {};
    data.itemStyle.emphasis.label = { show: labelOnEmphasis };
    data.itemStyle.emphasis.labelLine = { show: labelOnEmphasis };

    return data;
}
function setNestedSeries(series, showLabel, labelOnEmphasis) {

    if(!series || series.length == 0) return [];

    let data = [{
        name: series[0].name,
        type: 'pie',
        selectedMode: 'single',
        radius: [0, '50%'],
        itemStyle: {
            normal: {
                borderWidth: 2,
                borderColor: '#353f53',
                label: {
                    position: 'inner'
                },
                labelLine: {
                    show: false
                }
            }
        },
        data: series[0].data
    },
    {
        name: series[1].name,
        type: 'pie',
        radius: ['60%', '85%'],
        itemStyle: {
            normal: {
                borderWidth: 2,
                borderColor: '#353f53',
                label: {
                    show: showLabel
                },
                labelLine: {
                    show: showLabel
                }
            },
            emphasis: {
                label: {
                    show: labelOnEmphasis
                },
                labelLine: {
                    show: labelOnEmphasis
                }
            }
        },
        data: series[1].data
    }];

    return data;
}
function setSeriesNames(series, nested) {

    if(series.length == 0) return null;

    if(nested) {

        let nestedSeries;
        let innerSeries = series[0].data.map(function(item){ return item.name });
        let outerSeries = series[1].data.map(function(item){ return item.name });
        nestedSeries = innerSeries.concat(outerSeries);

        return nestedSeries;

    } else {
        return series.data.map(function(item){ return item.name });
    }
}
function setLegend(legendData) {
    return  {
        orient: 'vertical',
        top: 'center',
        left: 0,
        data: legendData,
        itemHeight: 8,
        itemWidth: 8,
        textStyle: {
            color: '#fff'
        }
    }
}
function setTitle(title, subtitle) {

    if(title == null) return null;

    return {
        text: title,
        subtext: subtitle,
        left: 'center',
        textStyle: {
            fontSize: 17,
            fontWeight: 500,
            color: '#fff'
        },
        subtextStyle: {
            fontSize: 12,
            color: '#fff'
        }
    }

}
function setTooltip() {
    return {
        trigger: 'item',
        backgroundColor: 'rgba(255,255,255,0.9)',
        padding: [10, 15],
        textStyle: {
            color: '#222',
            fontSize: 13,
            fontFamily: 'Roboto, sans-serif'
        },
        formatter: "{a} <br/>{b}: {c} ({d}%)"
    }
}
//#endregion

$(document).ready(function() { set_chart(); });