(function () {
    'use strict';

    angular.module('fehlerberichtApp')
        .controller('StatsCtrl', function ($scope, $http, $routeParams) {
            var webservice = 'db.php?';

            $scope.data = {};
            $scope.summary = {};
            $scope.options = {};
            $scope.customer = $routeParams.customer;

            $scope.refresh = function () {
                $scope.data = {};
                $scope.summary = {};
                $http.get(webservice + 'a=config&datum=current&kunde=' + $scope.customer).success(function (data) {
                    if (data.current) {
                        $scope.options.customer = _.keys(data.options);
                        $scope.data = data.current.info;

                        var reports = _.filter($scope.data.reports, function (row) {
                            return row.Datei.match(/ver/i) === null && row.GIF === 'N';
                        });
                        $scope.summary = {
                            '1. Portale': _.uniq(_.pluck(reports, 'Datei')),
                            '1.1 Analyse-User': _.uniq(_.pluck(_.filter(reports, function (row) {
                                return row.PDF === 'N';
                            }), 'Benutzer')),
                            '1.2 PDF-User': _.uniq(_.pluck(_.filter(reports, function (row) {
                                return row.PDF === 'J';
                            }), 'Benutzer')),
                            '1.3 Ebenen': _.uniq(_.pluck(reports, 'Struktur')),

                            '2. Versandintervalle': _.uniq(_.pluck($scope.data.versand, 'Datei')),
                            '2.1 Empfänger': _.uniq(_.sortBy(_.pluck($scope.data.versand, 'Empfaenger'), function (row) {
                                return row;
                            })),
                            '2.2 Reports': _.uniq(_.sortBy(_.pluck($scope.data.versand, 'Report'), function (row) {
                                return row;
                            })),

                            '3. Cubes': _.uniq(_.sortBy(_.filter(_.pluck($scope.data.ppr, 'Cube'), function (row) {
                                return row !== '';
                            }), function (row) {
                                return row;
                            })),
                            '4. Fehlende Reports': _.uniq(_.pluck(_.filter($scope.data.ppr, function (row) {
                                return row.PPR === 'fehlt' && row.Typ === 'PPR';
                            }), 'Report'))
                        };
                    }
                });
            };

            $scope.refresh();

            $scope.test = function (v) {
                return v.match(/(test|global-cube)/i);
            };
        }
    );
})();