//#region MAIN FUNCTIONS
function set_chart() {

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

    let chartCounter = 0;

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

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

        init_chart(elementChart[0].id);

    });

}

function init_chart(chartId) {

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

    if (chartElement) {

        // elementObject for the charts parameters
        // objectData for the chart data manager
        let elementObject = $(chartElement);
        let objectData = elementObject.attr('data') ? JSON.parse(elementObject.attr('data')) : null;

        let numberOfCharts = objectData?.charts ?? (elementObject.attr('charts') ?? 1);
        set_chart_height(numberOfCharts, chartElement)

        let chartInstance = echarts.init(chartElement);

        chartInstance.showLoading({
            text: 'LADE DATEN',
            maskColor: '#353f53',
            color: '#fff',
            textColor: '#fff',
            fontSize: 15
        });

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

// setting the data first checks for the data chart manager object and if specific attributes are not set then will use the chart element parameters. else defaults.
function set_data(objectData, elementObject, numberOfCharts, 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 = objectData?.rawData ?? (elementObject.attr('raw') ? JSON.parse(elementObject.attr('raw')) : null);

        if(rawData == null) {

            let multichart = (numberOfCharts > 1);

            // variables (this will be set by user)

            // unique attributes of line chart
            let titles = objectData?.titles ?? (JSON.parse(elementObject.attr('titles')) ?? []);
            let boundaryGap = objectData?.boundaryGap ?? (elementObject.attr('boundary-gap') == 'true' || elementObject.attr('boundary-gap') == true); // default true
            let inverted = objectData?.inverted ?? (elementObject.attr('inverted') == 'true' || elementObject.attr('inverted') == true); // default false
            let showDataZoom = objectData?.dataZoom ?? (elementObject.attr('data-zoom') == 'true' || elementObject.attr('data-zoom') == true); // default false
            let showPointValues = objectData?.pointValues ?? ((elementObject.attr('point-values') == 'true' || elementObject.attr('point-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 options
            let isArea = objectData?.isArea ?? ((elementObject.attr('is-area') == 'true' || elementObject.attr('is-area') == true) ?? false); // series data options
            let markLine = objectData?.markLine ?? (elementObject.attr('mark-line') ?? null); // min | max | average - series data options

            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, showPointValues, isArea);

            // Options
            options = {

                // Chart title
                title: setTitles(titles, numberOfCharts),

                // Define colors
                color: colors,

                // Global text styles
                textStyle: setGlobalTextStyle(),

                // Chart animation duration
                animationDuration: animationDuration,

                // Setup grid
                grid: setGrid(showDataZoom, numberOfCharts),

                // Add legend
                legend: setLegend(seriesNames, multichart),

                // Add tooltip
                tooltip: setTooltip(),

                // Horizontal axis
                xAxis: inverted ? setYAxis(yAxisLabelValueFormat, numberOfCharts) : setXAxis(categories, boundaryGap, numberOfCharts),

                // Vertical axis
                yAxis: inverted ? setXAxis(categories, boundaryGap, numberOfCharts) : setYAxis(yAxisLabelValueFormat, numberOfCharts),

                // Axis pointer
                axisPointer: setAxisPointer(multichart),

                // Add series
                series: seriesObject
            };

            if(showDataZoom == true) {
                options.dataZoom = setDataZoom(showDataZoom, multichart);
            }

        } else {
            options = rawData;
        }

        callback(options);

    }, 1000);

}

function set_chart_height(numberOfCharts, chartElement) {

    // adjust container height before initialising the chart.
    if (numberOfCharts > 1) {
        let height = (numberOfCharts * 240); // (chart height = 160 | charts spacing = 80)
        chartElement.style.height = height + 'px';
    }

    return chartElement;
}
//#endregion

//#region FUNCTIONS FOR OPTIONS

function setSeries(seriesData, stacked, markLine, showPointValues, isArea) {

    // setting the data first checks for the data chart manager object and if specific attributes are not set then will use the chart element parameters. else defaults.
    // uses series options if available else use chart manager or chart parameter settings

    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 ?? 'line',
            data: seriesData[i].data,
            stack: seriesData[i].stacked ?? stacked,
            smooth: true,
            symbol: 'circle',
            symbolSize: 7,
            label: {
                normal: {
                    show: seriesData[i].showPointValues ?? showPointValues
                }
            },
            itemStyle: {
                normal: {
                    borderWidth: 2
                }
            },
            xAxisIndex: seriesData[i].index ?? 0,
            yAxisIndex: seriesData[i].index ?? 0
        }

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

        seriesArray.push(series);

    }

    return seriesArray;
}

function setXAxis(categories, boundaryGap = true, numberOfCharts = 1) {

    let xAxisArray = [];
    for (let i = 0; i < numberOfCharts; i++) {

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

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

        xAxisArray.push(x);
    }

    return xAxisArray;
}

function setYAxis(yAxisLabelValueFormat,  numberOfCharts = 1) {

    let yAxisArray = [];
    for (let i = 0; i < numberOfCharts; i++) {

        let y = {
            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)']
                }
            },
            gridIndex: i
        };

        yAxisArray.push(y);
    }

    return yAxisArray;
}

// disabled when multichart is true
function setLegend(legendData, multichart = false) {
    return multichart ? null : {
        data: legendData,
        itemHeight: 8,
        itemGap: 20,
        textStyle: {
            color: '#fff'
        }
    }
}

function setTitles(titles, numberOfCharts = 1) {

    // if not array.
    if(!Array.isArray(titles)) {
        let temp = titles;
        titles = [];
        titles.push(temp);
    }

    let arrayTitles = [];

    for(let i = 0; i < numberOfCharts; i++) {

        let title = {
            text: titles[i],
        };

        // if single else multichart
        if(i == 0 && numberOfCharts == 1) {
            title.textStyle = {
                color: '#fff'
            };
        } else {
            title.textStyle = {
                fontSize: 15,
                fontWeight: 500,
                color: '#fff'
            };
            title.left = 'center';
            title.top = 240 * i; //  (chart height = 160 | charts spacing = 80) * index
        }

        arrayTitles.push(title);
    }

    return arrayTitles;
}

// disabled when multichart is true
function setDataZoom(show, multichart = false) {
    return multichart ? null : [
        {
            type: 'inside',
            start: 30,
            end: 70
        },
        {
            show: show,
            type: 'slider',
            start: 30,
            end: 70,
            height: 40,
            bottom: 0,
            borderColor: 'rgba(255,255,255,0.1)',
            fillerColor: 'rgba(0,0,0,0.1)',
            textStyle: {
                color: '#fff'
            },
            handleStyle: {
                color: '#8893a9'
            },
            dataBackground: {
                areaStyle: {
                    color: 'rgba(0,0,0,0.5)'
                }
            }
        }
    ]
}

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

function setGrid(showDataZoom = false, numberOfCharts = 1) {

    let arrayGrids = [];
    for (let i = 0; i < numberOfCharts; i++) {

        let grid = {
            left: 0,
            containLabel: true
        };

        // if single else multichart
        if(i == 0 && numberOfCharts == 1) {
            grid.right = 40;
            grid.top = 50;
            grid.bottom = showDataZoom ? 60 : 0;
        } else {
            grid.right = 20;
            grid.top = (i == 0) ? 40 : (arrayGrids[i-1].top + 240); // previous top + chart height = 160 + charts spacing = 80
            grid.height = 160;
        }

        arrayGrids.push(grid);
    }

    return arrayGrids;
}

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

function setAxisPointer(multichart = false) {
    let pointer =  {
        lineStyle: {
            color: 'rgba(255,255,255,0.25)'
        }
    };

    if(multichart) {
        pointer.link = {
            xAxisIndex: 'all'
        };
    }

    return pointer;
}
//#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),
            }]
        };

    }
}

function setArea(series, seriesData, isArea) {

    let area = seriesData.isArea ?? isArea;

    if(area == true) {
        series.areaStyle = {};
    }

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