{{!
    This file is part of Moodle - https://moodle.org/

    Moodle is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Moodle is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
}}
{{!
    @template biblocks_column/preview

    Example context (json):
    {
      "element_id": "12345",
      "chart_default": "{chart: 123}",
      "chart_options": "options = 123;",
      "code_util_get_js_theme": "options.config = 123;",
      "error_chart_renderer": "Erro ao renderizar o gráfico",
      "ajax_url": "https://example.com/chart_data",
      "error_data_loader": "Erro ao carregar os dados",
      "reload_time": "60000"
    }

}}

<div class="column-chart area-chart-column" id="chart_{{element_id}}"></div>

{{#js}}
    require(["jquery", "core/notification"], function($, Notification) {
        function showChart(xaxisCategories, series) {
            try {
                var options = {{{chart_default}}};

                {{{chart_options}}}

                var optionsData = {
                    xaxis: {
                        categories: xaxisCategories
                    },
                    series: series
                };
                options = {...options, ...optionsData};

                {{{code_util_get_js_theme}}}

                var element = document.querySelector("#chart_{{element_id}}");
                var chart = new ApexCharts(element, options);
                chart.render();
            }
            catch (e) {
                Notification.exception({message: "{{error_chart_renderer}}"});
            }
        }

        function loadDataChart() {
            $.ajax({
                dataType: "json",
                url: "{{{ajax_url}}}",
                success: function(json) {
                    showChart(json.xaxisCategories, json.series);
                },
                error: function() {
                    Notification.exception({message: "{{error_chart_renderer}}"});
                }
            });
        }

        loadDataChart();

        var reloadTime = parseInt("{{{reload_time}}}");
        if (reloadTime) {
            setInterval(loadDataChart, reloadTime);
        }
    });
{{/js}}
