let chartManager = new ChartManager();

//#region MAIN FUNCTIONS
function set_chart() {

    if(chartManager.isModuleSet() == false) 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 = chartManager.getObjectData(elementObject);

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

        let chartInstance = echarts.init(chartElement);

        chartInstance.showLoading(chartManager.defaultLoadingOptions);

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

    // 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.

    setTimeout(function() {

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

        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 isArea = objectData?.isArea ?? ((elementObject.attr('is-area') == 'true' || elementObject.attr('is-area') == true) ?? false); // series data options

            let yAxisLabelValueFormat = chartManager.getYAxisLabelValueFormat(objectData, elementObject);

            let stacked = chartManager.getSeriesStacked(objectData, elementObject);
            let markLine = chartManager.getSeriesMarkLine(objectData, elementObject);

            let categories = chartManager.getChartCategories(objectData, elementObject);
            let series = chartManager.getChartSeries(objectData, elementObject);

            let seriesNames = chartManager.getChartSeriesNames(series);
            let seriesObject = setSeries(series, stacked, markLine, showPointValues, isArea);

            // Options
            options = {

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

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

                // Global text styles
                textStyle: chartManager.defaultGlobalTextStyle,

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

                // 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
        }

        chartManager.setSeriesMarkLine(series, seriesData[i], markLine);
        setSeriesArea(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;
}
function setLegend(legendData, multichart = false) {

    // disabled when multichart is true

    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;
}
function setDataZoom(show, multichart = false) {

    // disabled when multichart is true

    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 setAxisPointer(multichart = false) {
    let pointer =  {
        lineStyle: {
            color: 'rgba(255,255,255,0.25)'
        }
    };

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

    return pointer;
}
function setSeriesArea(series, seriesData, isArea) {

    let area = seriesData.isArea ?? isArea;

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

}
//#endregion

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