//generateChart is a required function which will be called to generate your Javascript chart
generateChart = function(options) {
    //Example: call options.blockRenderComplete to let the report api know that their is an asynchronous action going on.
    options.blockRenderComplete();
    
    // This is the div you draw your chart into
    var $treemapDrawDiv = $(options.divSelector);

    // To stop scrollbars in any portlets regardless of your javascript, use this css class
    $treemapDrawDiv.addClass('jsChartNoOverflow');
    // This gets the height and width from the dataset. Use these when creating your chart so that
    // it will fit the dashboard, canvas and storyboard correctly
    
    var height = options.dataset.chart_information.height;
    var width = options.dataset.chart_information.width;


    // Do the actual drawing of the chart" "into $chartDiv.
    doDrawing(options.dataset.data, $treemapDrawDiv, height, width, options.errorCallback, options);
};

const doDrawing = function(data, $chartDiv, height, width, errorFunction, options) {
    
    const loadHighchartModule = async(moduleName) => {
        return import('https://code.highcharts.com/es-modules/masters/' + moduleName);
    };
    
     
     /**
      * Helper function to load any highcharts modules which may be required can be called. The base Highcarts module
      * will always be loaded
      *
      * loadHighchartsAndCreateChart(['module.js'], function(Highcharts) {
      *     //Create my charts
      * })
      *
      * If no dependencies are required, null can be passed for the files array
      *
      * loadHighchartsAndCreateChart(null, function() {
      *     //create my charts
      * });
      * }
      *
      * */
    const loadHighchartsAndCreateChart = async(files, onComplete) => {
        const {default: Highcharts} = await loadHighchartModule('highcharts.src.js');
        
        let filePromises = [];
        
        if(files) {
            for(let i = 0; i < files.length; i++) {
                filePromises.push(loadHighchartModule(files[i]));
            }
        }
        
        Promise.all(filePromises).then(() => {
            onComplete(Highcharts,options);
        });
        
    }
    
   
    loadHighchartsAndCreateChart(['modules/exporting.src.js','modules/accessibility.src.js','modules/treemap.src.js','modules/drilldown.src.js'], function(Highcharts, options) {
            var line, clickX, clickY;
            var $treemapDrawDiv = $chartDiv;
        
            //Simple Line Chart that displays - dimension, metric and a date along the xAxis
            //Change the values of these variables to point to other data in the dataset
            const DIMENSION = 'demographic';
            const METRIC = 'invoiced_amount';
            const DATE = 'year';
            
            let data = options.dataset.data;
            
            let seriesDataset = [];
            let chartMap = {};    
            
            let xAxisCategories = [];
            //Creating the seriesDataset and the xAxisCategories to be passed to HighCharts
            for(let i = 0; i < data[DIMENSION].length; i++) {
                let dimData = data[DIMENSION][i];
                let metricData = data[METRIC][i];
                let dateData = data[DATE][i];
                
                if(xAxisCategories.indexOf(dateData.formatted_data) == -1) {
                    xAxisCategories.push(dateData.formatted_data);
                }
                
                let existingData = chartMap[dimData.formatted_data];
                if(!existingData) {
                    chartMap[dimData.formatted_data] = {
                        name: dimData.formatted_data,
                        data: []
                    };
                    existingData = chartMap[dimData.formatted_data];
                    seriesDataset.push(existingData);
                }
                
                existingData.data.push(metricData.raw_data);
                
            }        
        
            // Create a test chart.
            window.chart = Highcharts.chart({
                
                chart: {
                    renderTo: $chartDiv[0],
                    height: height,
                    width: width,
                    events: {
                        load: function() {
                            /*
                                Example: Once the chart has completed rendering, we can now call options.renderComplete to signal to the PDF exporter that 
                                this is complete.
                            */
                            options.renderComplete();
                            
                        }               
                    }
                },

                plotOptions: {
                    series: {
                        cursor: 'pointer',
                        animation: false,
                    }
                },
                
                series: seriesDataset,
                xAxis: {
                    categories: xAxisCategories
                },
                
                credits: {
                    enabled: false
                }
            });
    });
};

