//#region MAIN FUNCTIONS
function set_chart() {

    if (typeof echarts == 'undefined') {
        console.warn('Warning - echarts.min.js is not loaded.');
        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({
            text: 'LADE DATEN',
            maskColor: '#353f53',
            color: '#fff',
            textColor: '#fff',
            fontSize: 15
        });

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

function set_data(elementObject, callback) {

    setTimeout(function() {

        const defaultColors = [
            '#2ec7c9','#b6a2de','#5ab1ef','#ffb980','#d87a80',
            '#8d98b3','#e5cf0d','#97b552','#95706d','#dc69aa',
            '#07a2a4','#9a7fd1','#588dd5','#f5994e','#c05050',
            '#59678c','#c9ab00','#7eb00a','#6f5553','#c14089',
            '#66bb6a'
        ];

        let options;
        let rawData = elementObject.attr('raw') ? JSON.parse(elementObject.attr('raw')) : null;

        if(rawData == null) {

            // variables (this will be set by user)
            let title = elementObject.attr('title') ?? null;
            let subtitle = elementObject.attr('subtitle') ?? null;
            let colors = JSON.parse(elementObject.attr('colors')) ?? defaultColors;
            let donut = (elementObject.attr('donut') == 'true' || elementObject.attr('donut') == true);
            let animationDuration = elementObject.attr('animation-duration') ?? 750;

            let series = JSON.parse(elementObject.attr('series')) ?? null;
            let seriesNames = series && series.data.map(function(item){ return item.name });
            let seriesObject = setSeries(series, donut);


            // Options
            options = {

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

                // Define colors
                color: colors,

                // Global text styles
                textStyle: setGlobalTextStyle(),

                // Chart animation duration
                animationDuration: animationDuration,

                // 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, donut) {

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

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

    return data;
}

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}%)"
    }
}

function setGlobalTextStyle() {
    return {
        fontFamily: 'Roboto, Arial, Verdana, sans-serif',
        fontSize: 13
    };
}

//#endregion

function setResizeEvent(chartElement, chartInstance) {
    // Resize function
    let triggerChartResize = function() {
        chartElement && chartInstance.resize();
    };

    // On sidebar width change
    let sidebarToggle = document.querySelector('.sidebar-control');
    sidebarToggle && sidebarToggle.addEventListener('click', triggerChartResize);

    // On window resize
    let resizeCharts;
    window.addEventListener('resize', function() {
        clearTimeout(resizeCharts);
        resizeCharts = setTimeout(function () {
            triggerChartResize();
        }, 200);
    });
}

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