var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

/* global _, booyah, accounting */

Booyah.$charts = $('.booyah-chart');

// -----------------------------------------------------------------------------
// Bar Charts

Booyah.$charts.filter('.booyah-chart--bar').each(function () {
    var $chart = $(this);
    if (typeof $chart.data('url') !== 'undefined') {
        $chart.dataUrl = $chart.data('url');
    } else if (typeof $chart.data('url-key') !== 'undefined') {
        $chart.dataUrl = booyah.getAjaxRoute($chart.data('url'));
    } else {
        console.warn('Keine URL für die Chart-Daten hinterlegt.');
        return;
    }
    $chart.$info = $chart.prev('.alert-info');
    $chart.dataKey = $chart.data('key');
    $chart.tmpId = Booyah.randomId;
    $chart.kpi = typeof $chart.data('kpi') === 'undefined' ? '' : $chart.data('kpi');
    $chart.dateFormat = $chart.data('date-format');
    $chart.timeFormat = $chart.data('time-format');
    $chart.categoryLabels = [];
    $chart.init = function () {
        this.attr('id', this.tmpId);
        var chartConf = {
            type: 'serial',
            theme: 'light',
            dataProvider: [],
            gridAboveGraphs: false,
            startDuration: 1,
            thousandsSeparator: '.',
            decimalSeparator: ',',
            graphs: [{
                fillAlphas: 0.8,
                lineAlpha: 0.2,
                type: "column",
                valueField: '1',
                balloonFunction: $chart.balloonFunction
            }],
            chartCursor: {
                categoryBalloonEnabled: false,
                cursorAlpha: 0,
                zoomable: false
            },
            categoryField: "date",
            categoryAxis: {
                gridPosition: "start",
                gridAlpha: 0,
                tickPosition: "start",
                tickLength: 0,
                labelFunction: function labelFunction(valueText) {
                    var label = '';
                    if (typeof valueText !== 'undefined') {
                        if (valueText.toString().trim() !== '') {
                            if (typeof $chart.categoryLabels[valueText] !== 'undefined') {
                                label = $chart.categoryLabels[valueText];
                            } else {
                                var formatedDate = $chart.formatDate(moment(valueText, 'YYYY-MM-DD HH:mm:SS').locale(Booyah.locale));
                                if (formatedDate.split('.')[0] !== 'NaN') {
                                    label = formatedDate;
                                }
                            }
                        }
                    }

                    return label;
                }
            },
            valueAxes: [{
                labelFunction: $chart.valueAxesLabel
            }],
            export: {
                "enabled": false
            }
        };

        chartConf.colors = [booyah.getThemeColor('primary'), booyah.getThemeColor('secondary'), booyah.getThemeColor('info'), booyah.getThemeColor('warning'), booyah.getThemeColor('danger')];

        this.chart = AmCharts.makeChart($chart.tmpId, chartConf);
    };

    $chart.onError = function () {};

    $chart.balloonFunction = function (graphData) {
        var valueField = graphData.graph.valueField;
        var value = parseFloat(graphData.dataContext[valueField]);

        return AmCharts.formatNumber(Math.abs(value), {
            precision: 2,
            decimalSeparator: ',',
            thousandsSeparator: '.'
        }) + ' ' + $chart.kpi;
    };

    $chart.valueAxesLabel = function (valueText) {
        return valueText + ' ' + $chart.kpi;
    };

    $chart.formatDate = function (date) {
        var formatedDate = void 0;
        if (typeof $chart.dateFormat !== 'undefined' && typeof $chart.timeFormat !== 'undefined') {
            formatedDate = date.format($chart.dateFormat + ' ' + $chart.timeFormat);
        } else if (typeof $chart.dateFormat !== 'undefined') {
            formatedDate = date.format($chart.dateFormat);
        } else if (typeof $chart.timeFormat !== 'undefined') {
            formatedDate = date.format($chart.timeFormat);
        } else {
            formatedDate = date.format('DD.MM.YYYY');
        }

        return formatedDate;
    };

    $chart.update = function (chartData) {
        if (typeof chartData.data === 'undefined') {
            $chart.onError();
            return;
        }

        if (typeof chartData.kpi !== 'undefined') {
            this.kpi = chartData.kpi;
        }

        if (typeof chartData.categoryLabels !== 'undefined') {
            this.categoryLabels = chartData.categoryLabels;
        }

        var dateRange = typeof chartData.dateRange !== 'undefined' ? chartData.dateRange : 'month';
        var graphAlpha = typeof chartData.graphAlpha !== 'undefined' ? chartData.graphAlpha : 1;
        /***********************************************************************************************
         * >> CHART GRAPHS
         */
        var valueKeys = [];
        var dataProvider = [];
        var graphs = [];

        $.each(chartData.data, function (reading_at, values) {
            var newProvider = {
                date: reading_at
            };
            $.each(values, function (key, keyData) {
                if ((typeof keyData === 'undefined' ? 'undefined' : _typeof(keyData)) === 'object') {
                    newProvider[key] = keyData.value;
                    if (typeof keyData.color !== 'undefined') {
                        newProvider['color_' + key] = $chart.rgb2Hex(booyah.getThemeColor(keyData.color));
                    }
                } else {
                    newProvider[key] = keyData;
                }
                if ($.inArray(key, valueKeys) <= -1 && $.inArray(key, ['categoryLabel']) === -1) {
                    valueKeys.push(key);
                }
            });
            dataProvider.push(newProvider);
        });

        $.each(valueKeys, function (inx, key) {
            var graph = {
                id: inx,
                fillAlphas: graphAlpha,
                lineThickness: 0,
                valueField: key,
                colorField: 'color_' + key,
                dateFormat: 'MM.YYYY',
                type: 'column',
                balloonFunction: $chart.balloonFunction
            };
            graphs.push(graph);
        });
        /**
         * << CHART GRAPHS
         ***********************************************************************************************/

        /***********************************************************************************************
         * >> CHART GUIDES
         */
        var guides = [];
        if (_typeof(chartData.days) === 'object') {
            /***********************************************************************************************
             * >>> CHART GUIDES WEEKENDS
             */
            if (_typeof(chartData.days.weekends) === 'object') {
                var weekendGuides = [];
                $.each(chartData.days.weekends, function (inx, weekend) {
                    var date = Booyah.dateWithOffset(new Date(weekend));
                    var toDate = Booyah.dateWithOffset(new Date(weekend));
                    toDate.setDate(toDate.getDate() + 1);
                    var prevDate = Booyah.dateWithOffset(new Date(weekend));
                    prevDate.setDate(prevDate.getDate() - 1);
                    if (weekendGuides.length && Booyah.getDateString(date) === weekendGuides[weekendGuides.length - 1].toDate) {
                        weekendGuides[weekendGuides.length - 1].toDate = Booyah.getDateString(toDate);
                    } else {
                        weekendGuides.push({
                            date: Booyah.getDateString(date),
                            toDate: Booyah.getDateString(toDate),
                            lineColor: booyah.getThemeColor('dark'),
                            lineAlpha: 0,
                            fillAlpha: 0.075,
                            fillColor: booyah.getThemeColor('dark'),
                            dashLength: 4,
                            inside: true,
                            labelRotation: 90,
                            label: ''
                        });
                    }
                });
                guides = guides.concat(guides, weekendGuides);
            }

            /**
             * <<< CHART GUIDES WEEKENDS
             ***********************************************************************************************/
            /***********************************************************************************************
             * >>> CHART GUIDES HOLIDAYS
             */
            if (_typeof(chartData.days.holidays) === 'object') {
                var holidayGuides = [];
                $.each(chartData.days.holidays, function (inx, holiday) {
                    var date = Booyah.dateWithOffset(new Date(inx));
                    var toDate = Booyah.dateWithOffset(new Date(inx));
                    toDate.setDate(toDate.getDate() + 1);
                    holidayGuides.push({
                        date: Booyah.getDateString(date),
                        toDate: Booyah.getDateString(toDate),
                        lineColor: booyah.getThemeColor('danger'),
                        lineAlpha: 0,
                        fillAlpha: 0.075,
                        fillColor: booyah.getThemeColor('danger'),
                        dashLength: 4,
                        inside: true,
                        labelRotation: 90,
                        label: holiday
                    });
                });
                guides = guides.concat(guides, holidayGuides);
            }
            /**
             * <<< CHART GUIDES HOLIDAYS
             ***********************************************************************************************/
        }
        /**
         * << CHART GUIDES
         ***********************************************************************************************/
        if (dataProvider.length && graphs.length) {
            this.chart.graphs = graphs;
            this.chart.dataProvider = dataProvider;
            this.chart.guides = guides;
            if (dateRange === 'month') {
                this.chart.categoryAxis.minPeriod = 'MM';
            } else if (dateRange === 'day') {
                this.chart.categoryAxis.minPeriod = 'DD';
            } else {
                this.chart.categoryAxis.minPeriod = 'mm';
            }

            this.chart.validateData();
            $chart.show();
        } else {
            this.chart.dataProvider = [];
            this.chart.validateData();
            if ($chart.$info.length) {
                $chart.$info.removeClass('d-none');
            }
            $chart.hide();
        }
    };

    $chart.rgb2Hex = function (rgb) {
        if (rgb.indexOf('rgb') !== 0) {
            return rgb;
        }
        return AmCharts.rgb2hex(rgb);
    };

    $chart.loadData = function () {
        if ($chart.$info.length) {
            $chart.$info.addClass('d-none');
        }
        Booyah.toggleCardLoader($chart.parents('.card'));
        $.get($chart.dataUrl).done(function (chartData) {
            $chart.update(chartData);
        }).fail(function () {
            if ($chart.$info.length) {
                $chart.$info.addClass('d-none');
            }
        }).always(function () {
            Booyah.toggleCardLoader($chart.parents('.card'));
        });
    };

    $chart.init();
    $chart.loadData();
});
