(function ($) {
    window.StatsGroup = function (url, target) {
        // a class to properly display statictics

        // url : points to an ObjectResumeStat that lists the options through JSON
        // target : element of the DOM where to put the stats

        var element = $(target);
        var content = $("<div class='full'>");
        var buttons;

        function handleTimeChart(data) {
            // reads the balance data and put it into chartjs formatting
            chart_data = new Array();
            for (var i = 0; i < data.length; i++) {
                var source = data[i];
                chart_data[i] = {
                    x: new Date(source.at),
                    y: source.balance,
                    label: source.label,
                }
            }
            return chart_data;
        }

        function showStats() {
            // CALLBACK : called when a button is selected

            // shows the focus on the correct button
            buttons.find(".focus").removeClass("focus");
            $(this).addClass("focus");

            // loads data and shows it
            $.getJSON(this.stats_target_url, displayStats);
        }

        function displayStats(data) {
            // reads the json data and updates the chart display

            var chart_datasets = [];
            // are the points indexed by timestamps?
            var is_time_chart = data.is_time_chart || false;

            // reads the charts data
            for (let chart of data.charts) {
                // format the data
                var chart_data = is_time_chart ? handleTimeChart(chart.values) : chart.values;

                chart_datasets.push(
                    {
                        label: chart.label,
                        borderColor: chart.color,
                        fill: is_time_chart,
                        lineTension: 0,
                        data: chart_data,
                        steppedLine: is_time_chart,
                    });
            }

            // options for chartjs
            var chart_options =
            {
                responsive: true,
                maintainAspectRatio: false,
                tooltips: {
                    mode: 'index',
                    intersect: false,
                },
                hover: {
                    mode: 'nearest',
                    intersect: false,
                }
            };

            // additionnal options for time-indexed charts
            if (is_time_chart) {
                chart_options['scales'] = {
                    xAxes: [{
                        type: "time",
                        time: {
                            tooltipFormat: 'll HH:mm',
                            displayFormats: {
                                'millisecond': 'SSS [ms]',
                                'second': 'mm:ss a',
                                'minute': 'DD MMM',
                                'hour': 'ddd h[h]',
                                'day': 'DD MMM',
                                'week': 'DD MMM',
                                'month': 'MMM',
                                'quarter': 'MMM',
                                'year': 'YYYY',
                            }
                        }

                    }],
                };
            }

            // global object for the options
            var chart_model =
            {
                type: 'line',
                options: chart_options,
                data: {
                    labels: data.labels || [],
                    datasets: chart_datasets,
                }
            };

            // saves the previous charts to be destroyed
            var prev_chart = content.children();

            // clean
            prev_chart.remove();

            // creates a blank canvas element and attach it to the DOM
            var canvas = $("<canvas height='250'>");
            content.append(canvas);

            // create the chart
            var chart = new Chart(canvas, chart_model);
        }

        // initialize the interface
        function initialize(data) {
            // creates the bar with the buttons
            buttons = $("<ul>",
                {
                    class: "nav stat-nav",
                    "aria-label": "select-period"
                });

            var to_click;

            for (let stat of data.stats) {
                // creates the button
                var btn_wrapper = $("<li>", { role: "presentation" });
                var btn = $("<a>",
                    {
                        class: "btn btn-nav",
                        type: "button"
                    })
                    .text(stat.label)
                    .prop("stats_target_url", stat.url)
                    .on("click", showStats);

                // saves the default option to select
                if (stat.default)
                    to_click = btn;

                // append the elements to the parent
                btn_wrapper.append(btn);
                buttons.append(btn_wrapper);
            }

            // appends the contents to the DOM
            element.append(buttons);
            element.append(content);

            // shows the default chart
            to_click.click();
        };

        // constructor
        (function () {
            $.getJSON(url, initialize);
        })();
    };
})(jQuery);
