//#region MAIN FUNCTIONS
function set_chart() {

    if (typeof echarts == 'undefined') {
        console.warn('Warning - echarts.min.js is not loaded.');
        return;
    }

    let chartCounter = 0;

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

        chartCounter++;
        let elementChart = $(this);
        elementChart.attr('id', 'LimitlessBarChart' + 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 objectData = elementObject.attr('data') ? JSON.parse(elementObject.attr('data')) : null;
        let rawData = objectData?.rawData ?? (elementObject.attr('raw') ? JSON.parse(elementObject.attr('raw')) : null);

        if(rawData == null) {

            // variables (this will be set by user)

            // unique attributes of bar chart
            let title = objectData?.title ?? (elementObject.attr('title') ?? null);
            let horizontal = objectData?.horizontal ?? (elementObject.attr('horizontal') == 'true' || elementObject.attr('horizontal') == true); // default false
            let showBarValues = objectData?.barValues ?? ((elementObject.attr('bar-values') == 'true' || elementObject.attr('bar-values') == true) ?? false); // series data option

            let colors =  objectData?.colors ?? (JSON.parse(elementObject.attr('colors')) ?? defaultColors);
            let animationDuration = objectData?.animationDuration ?? (elementObject.attr('animation-duration') ?? 750);
            // ex '{value} users'  - https://echarts.apache.org/en/option.html#yAxis.axisLabel.formatter
            let yAxisLabelValueFormat = objectData?.yAxisLabelValueFormat ?? (elementObject.attr('y-axis-label-value-format') ?? null);

            let stacked = objectData?.stacked ?? ((elementObject.attr('stacked') == 'true' || elementObject.attr('stacked') == true) ?? false); // series data option
            let markLine = objectData?.markLine ?? (elementObject.attr('mark-line') ?? null); // min | max | average - series data option

            let categories = objectData?.categories ?? (JSON.parse(elementObject.attr('categories')) ?? null);
            let series = objectData?.series ?? (JSON.parse(elementObject.attr('series')) ?? null);

            let seriesNames = series && series.map(function(item){ return item.name });
            let seriesObject = setSeries(series, stacked, markLine, showBarValues, horizontal);

            // Options
            options = {

                // Chart title
                title: setTitle(title),

                // Define colors
                color: colors,

                // Global text styles
                textStyle: setGlobalTextStyle(),

                // Chart animation duration
                animationDuration: animationDuration,

                // Setup grid
                grid: setGrid(),

                // Add legend
                legend: setLegend(seriesNames),

                // Add tooltip
                tooltip: setTooltip(),

                // Horizontal axis
                xAxis: horizontal ? setYAxis(yAxisLabelValueFormat) : setXAxis(categories),

                // Vertical axis
                yAxis: horizontal ? setXAxis(categories) : setYAxis(yAxisLabelValueFormat),

                // Add series
                series: seriesObject
            };

        } else {
            options = rawData;
        }

        callback(options);

    }, 1000);

}
//#endregion

//#region FUNCTIONS FOR OPTIONS
function setSeries(seriesData, stacked, markLine, showBarValues, horizontal = false) {

    // uses series options if available else use global options.
    let seriesArray = [];

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

    for(let i = 0; i < seriesData.length; i++) {

        let series = {
            name: seriesData[i].name,
            type: seriesData[i].type ?? 'bar',
            data: seriesData[i].data,
            stack: seriesData[i].stacked ?? stacked,
            itemStyle: {
                normal: {
                    label: {
                        show: seriesData[i].showBarValues ?? showBarValues,
                        position: horizontal ? 'insideRight' : 'top',
                        textStyle: {
                            fontWeight: 500
                        }
                    }
                }
            },
        }

        setMarkLine(series, seriesData[i], markLine);

        seriesArray.push(series);

    }

    return seriesArray;
}

function setXAxis(categories) {

    let x = {
        type: 'category',
        axisLabel: {
            color: '#fff'
        },
        axisLine: {
            lineStyle: {
                color: 'rgba(255,255,255,0.25)'
            }
        },
        splitLine: {
            show: true,
            lineStyle: {
                color: 'rgba(255,255,255,0.1)',
                type: 'dashed'
            }
        }
    };

    if(categories != null) {
        x.data = categories;
    }

    return x;
}

function setYAxis(yAxisLabelValueFormat) {

    return {
        type: 'value',
        axisLabel: {
            formatter: yAxisLabelValueFormat,
            color: '#fff'
        },
        axisLine: {
            lineStyle: {
                color: 'rgba(255,255,255,0.25)'
            }
        },
        splitLine: {
            lineStyle: {
                color: 'rgba(255,255,255,0.1)'
            }
        },
        splitArea: {
            show: true,
                areaStyle: {
                color: ['rgba(255,255,255,0.01)', 'rgba(0,0,0,0.01)']
            }
        }
    };
}

function setLegend(legendData) {
    return {
        data: legendData,
        itemHeight: 8,
        itemGap: 20,
        textStyle: {
            color: '#fff'
        }
    }
}

function setTitle(title) {

    if(title == null) return null;

    return {
        text: title,
        textStyle: {
            color: '#fff'
        }
    }

}

function setTooltip() {
    return {
        trigger: 'axis',
        backgroundColor: 'rgba(255,255,255,0.9)',
        padding: [10, 15],
        textStyle: {
            color: '#222',
            fontSize: 13,
            fontFamily: 'Roboto, sans-serif'
        },
        axisPointer: {
            type: 'shadow',
            shadowStyle: {
                color: 'rgba(255,255,255,0.1)'
            }
        }
    }
}

function setGrid() {

    return {
        left: 0,
        right: 40,
        top: 50,
        containLabel: true
    };

}

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

//#region SUB FUNCTIONS FOR SERIES
function setMarkLine(series, seriesData, markLine) {
    if(seriesData.markLine !== undefined && ['min', 'max', 'average'].includes(markLine)) {

        series.markLine = {
            data: [{
                type: seriesData.markLine,
                name: seriesData.markLine[0].toUpperCase() + seriesData.markLine.substring(1),
            }]
        };

    } else if(markLine != null && ['min', 'max', 'average'].includes(markLine)) {

        series.markLine = {
            data: [{
                type: markLine,
                name: markLine[0].toUpperCase() + markLine.substring(1),
            }]
        };

    }
}
//#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(); });