'use strict';

/**
 * @ngdoc function
 * @name fehlerberichtApp.controller:AboutCtrl
 * @description
 * # AboutCtrl
 * Controller of the fehlerberichtApp
 */
angular.module('fehlerberichtApp')
    .controller('OverviewCtrl', function ($scope, $http, $routeParams, $interval) {
        var webservice = 'db.php?';

        var PERIOD_VISIBLE = 60 * 1000;
        var PERIOD_NOT_VISIBLE = 5 * 60 * 1000;

        $scope.error = {
            'level': -1,
            'info': [],
            'message': ""
        };

        $scope.domain = {
            'bearbeitet': {
                '0': "angesehen",
                '1': "behoben",
                '2': "zugeteilt",
                '3': "Rücksprache mit Kunde",
                '4': "Serverproblem",
                '5': "Prozess läuft",
                '6': "ignoriert / egal",
                '7': "weitergeleitet"
            },
            'comment': {
                '0': "glyphicon-eye-open",
                '1': "glyphicon-ok",
                '2': "glyphicon-user",
                '3': "glyphicon-earphone",
                '4': "glyphicon-flash",
                '5': "glyphicon-refresh",
                '6': "glyphicon-remove",
                '7': "glyphicon-share-alt"
            },
            'statusfilter': {
                '2': 'nicht behoben',
                '5': 'läuft',
                '6': 'ignoriert'
            },
            'fehler': {
                '0': "okay",
                '1': "fehlerhaft"
            },
            'system': [
                '?',
				'ARI',
                'AUDEV',
				'AUTOLINE',
				'CARLO',
				'HS',
				'LOCOSOFT',
				'NAVISION',
				'OPTIMA',
				'WERWISO',
				'Autosys',
				'Filaks',
				'O21-Light'
            ],
			'sys': {
                '?': '?',
				'ARI': 'AI',
                'AUDEV_CARIT': 'AC',
				'AUTOLINE': 'AL',
				'CARLO': 'C',
				'HS': 'HS',
				'LOCOSOFT': 'LO',
				'NAVISION': 'NV',
				'OPTIMA': 'O',
				'WERWISO': 'W',
				'Autosys': 'AS',
				'Filaks': 'F',
				'Optima-Light': 'OL'
            },
            'datum': {},
            'kunde': {},
            'status': {
                'errors': '1',
                'all': '',
                'missing': '',
                'flawless': '0'
            },
            'fehlend': {
                '1': 'fehlt',
                '0': 'vorhanden'
            },
            'date': {
                'all': moment().subtract(32, 'days').format('YYYY-MM-DD'),
                'today': moment().format('YYYY-MM-DD'),
                'yesterday':  moment().subtract(1, 'days').format('YYYY-MM-DD')
            },
            'benutzer': []
        };

        $scope.benutzer = window.localStorage.getItem("Benutzer");
        $scope.benutzer2 = 'bitte auswählen';

        $scope.overview = [];
        $scope.comments = {};
        $scope.comments2 = {};

        $scope.datum = [];

        $scope.current = {
            'zeile' : {},
            'fehler': {},
            'details': null,
            'status': 2,
            'kommentar': {},
            'fehlerdetails': null
        };

        $scope.Filter = {
            'kunde': ($routeParams.customer === 'all' || _.contains($scope.domain.system, $routeParams.customer)) ? '' : $routeParams.customer,
            'fehler': $scope.domain.status[$routeParams.status],
            'fehlend': ($routeParams.status === 'missing') ? '1' : '',
            'system': (_.contains($scope.domain.system, $routeParams.customer)) ? $routeParams.customer : '',
            'benutzer': ''
        };

        $scope.DatumFilter = {
            'von': (moment($routeParams.date, 'YYYY-MM-DD').isValid()) ? $routeParams.date : $scope.domain.date[$routeParams.date],
            'bis': moment().format('YYYY-MM-DD'),
            'datum': function (z) {
                return z.datum >= $scope.DatumFilter.von && z.datum <= $scope.DatumFilter.bis;
            }
        };

        $scope.Predicate = (function () {
            if ($routeParams.customer !== 'all') {
                return 'datum';
            }
            if ($routeParams.date === 'today' && $routeParams.status === 'errors') {
                    return 'ende_soll';
            }
            return ['kunde','datum'];
        })();

        $scope.Reverse = ($routeParams.customer !== 'all');

        $scope.SearchText = '';

        $scope.removeItem = function (index) {
            // Beispiel
            $scope.Bestellungen = $scope.Bestellungen.splice(index, 1);
        };

        $http.get(webservice + 'a=benutzer').success(function (data) {
            $scope.domain.benutzer = _.unique(_.pluck(data, 'benutzer'));
        });

        $http.get(webservice + 'a=kommentar&kunde=' + $scope.Filter.kunde + '&datum=' + $scope.DatumFilter.von + '&datum_bis=' + $scope.DatumFilter.bis).success(function (data) {
            $scope.comments = _.groupBy(data, 'kunde');
            $scope.comments2 = _.indexBy(data, 'id');
        });

        $scope.refresh = function () {
            $http.get(webservice + 'a=liste&kunde=' + $scope.Filter.kunde + '&datum=' + $scope.DatumFilter.von + '&datum_bis=' + $scope.DatumFilter.bis).success(function (data) {
                if (JSON.stringify($scope.overview) !== JSON.stringify(data)) {
                    $scope.overview = data;
                }
                //$scope.domain.benutzer = _.unique(_.pluck(data, 'benutzer'));
            });
        };

        $scope.importData = function () {
            $scope.error.level = 0;
            $scope.error.message = "Aktualisierung läuft!";
            $http.get('http://rbs06/GlobalCube/Fehlerbericht/app/import.php').success(function (data) {
                if (Array.isArray(data)) {
                    $scope.error.info = data;
                    if (data.length === 0) {
                        $scope.error.level = 0;
                        $scope.error.message = "Keine neuen Datensätze!";
                    } else {
                        $scope.error.message = "Neue Datensätze:";
                        $scope.error.level = 0;
                        $scope.refresh();
                    }
                } else {
                    $scope.error.info = [];
                    $scope.error.level = 1;
                    $scope.error.message = data;
                }
            });
        };

        $scope.refresh();

        var refreshTimer = $interval($scope.refresh, PERIOD_VISIBLE);
        if (document.addEventListener) {
            document.addEventListener("visibilitychange", visibilityChanged);
        }

        function visibilityChanged() {
            $interval.cancel(refreshTimer);
            if (document.visible) {
                $scope.refresh();
            }
            refreshTimer = $interval($scope.refresh, (document.hidden) ? PERIOD_NOT_VISIBLE : PERIOD_VISIBLE);
        }


        $scope.minuten = function (t) {
            var faktor, m, mins;
            if (!t) {
                return '';
            }
            faktor = 1;
            if (t < '00:00:00') {
                t = t.substring(1);
                faktor = -1;
            }
            m = moment(t, 'HH:mm:ss');
            mins = faktor * (m.minutes() + m.hours() * 60);
            return mins + " Min.";
        };

        $scope.timeDiffStart = function (z) {

            if (z.start === null) {
                return '';
            }
            var duration = moment.duration(z.start, 'HH:mm:ss').subtract(moment(z.start_soll, 'HH:mm:ss')).asMinutes();
            if (duration !== 0) {
                var plus = (duration > 0) ? '+' : '';
                return plus + duration + ' Minuten';
            }
            return '';
        };

        $scope.timeDiff = function (z) {

            if (z.start === null) {
                return '';
            }
            var duration = moment.duration(z.ende, 'HH:mm:ss').subtract(moment(z.ende_soll, 'HH:mm:ss')).asMinutes() - moment.duration(z.start, 'HH:mm:ss').subtract(moment(z.start_soll, 'HH:mm:ss')).asMinutes();
            if (duration !== 0) {
                var plus = (duration > 0) ? '+' : '';
                return '(' + plus + duration + ' Min.)';
            }
            return '';
        };

        $scope.dateFormat = function (date) {
            var d = moment(date, 'YYYY-MM-DD');
            if (d.isValid()) {
                if (date === $scope.domain.date.today) {
                    return 'Heute';
                }
                if (date === $scope.domain.date.yesterday) {
                    return 'Gestern';
                }
                return d.format('dd, DD.MM.YYYY');
            }
            return date;
        };

        $scope.dateTimeFormat = function (date) {
            var d = moment(date, 'YYYY-MM-DD HH:mm:ss');
            if (d.isValid()) {
                return d.format('DD.MM.YYYY, HH:mm');
            }
            return date;
        };

        $scope.timeFormat = function (t) {
            var d = moment(t, 'YYYY-MM-DD HH:mm:ss');
            if (d.isValid()) {
                return d.format('HH:mm:ss');
            }
            return t;
        };

        $scope.mailFormat = function (t) {
            if (t === undefined) {
                return '';
            }
            return _.map(t.split(';'), function (e) { return '<a href="mailto:' + e + '">' + e + '</a>'; }).join('<br/>');
        };

        $scope.left = function (text, length) {
            if (text.length === 0) {
                return '?';
            }
            return text.substring(0, length);
        };


        $scope.errorCount = function (e) {
            if (e === null) {
                return '0';
            }
            if (e.LastChangedDays > 0) {
                return $scope.daysCount(e);
            }
			if (e.Errors.length === 0) {
				if(e.Sources.length === 0) {
					return "Transformer-Protokollierung unvollständig";
				}
				else if (e.Summary === null) {
					return "Cube nicht erstellt, Protokoll fehlerhaft";
				}
			} 
			if (e.Errors.length === 1 && e.Type === "Modell" && e.Errors[0].Message !== null && e.Errors[0].Message.indexOf("has been deployed") > 0) {
				return "Transformer-Protokollierung im falschen Format (englisch)";
			}
            var type = 'Info';
            if (e.ErrorLevel < 3) {
                type = 'Fehler';
            }
            return _.values(e.Errors).length + ' ' + type;
        };

        $scope.daysCount = function (e) {
            if (e.LastChangedDays === 0) {
                return '0';
            }
            return e.LastChangedDays + ' Tage alt';
        };

        $scope.errorLevel = function (e) {
            return e.ErrorLevel <= 2 || e.Name.indexOf('bat') > -1 || e.LastChangedDays >= 3;
        };

        $scope.setCurrent = function (row) {
            $scope.current.zeile = row;
            $scope.current.fehler = {};
            $scope.current.details = null;
            $scope.current.fehlerdetails = null;
            $scope.current.limit = 7;

            $scope.current.status = 2;
            $scope.current.kommentar = {};
            $scope.current.template = {
                'id': '',
                'datum': row.datum,
                'kunde': row.kunde,
                'start': row.start,
                'benutzer': $scope.benutzer,
                'fehler': (row.anzahl === null) ? 0 : parseInt(row.anzahl, 10),
                'status': '0',
                'kommentar': '',
                'benutzer2': ''
            };

            $http.get(webservice + 'a=liste&kunde=' + $scope.current.zeile.kunde + '&datum=').success(function (data) {
                $scope.current.overview = data;
            });

            $http.get(webservice + 'a=fehlerbericht&kunde=' + $scope.current.zeile.kunde + '&datum=' + $scope.current.zeile.datum + '&start=' + $scope.current.zeile.start).success(function (data) {
                $scope.current.fehler = data;
                if (data.whitelist === undefined || data.whitelist === null) {
                    data.whitelist = {
                        'User': [],
                        'Report': [],
                        'Layer': []
                    };
                }

				if (data.kommentar.id !== undefined) {
                    $scope.current.kommentar = data.kommentar;
                    $scope.current.kommentar.fehler = parseInt(data.kommentar.fehler, 10);
                } else {
                    $scope.current.kommentar = $scope.current.template;
                }
				
				if (data.fehlerbericht === undefined) {
                    return;
                }
                data.fehlerbericht = _.sortBy(data.fehlerbericht, function(e) { return moment(e.Modified); });
                data.weitere = _.chain(data.fehlerbericht).reject($scope.errorLevel).groupBy(function (e) { return e.Type; }).value();

                var duration = _.map(_.filter(data.fehlerbericht, function (e) { return e.Summary !== null && e.Summary.Duration !== null && e.Summary.Duration >= '00:01:00'; }), function(e) { return { 'title': e.Type + ': ' + e.Name + ' (' + e.Summary.Duration + ')', 'value':  Math.ceil(moment.duration(e.Summary.Duration, 'HH:mm:ss').asMinutes()) }; });

                var chart = AmCharts.makeChart( "durationChart", {
                    "type": "pie",
                    "theme": "light",
                    "dataProvider": duration,
                    "titleField": "title",
                    "valueField": "value",
                    "labelRadius": 5,

                    "radius": "35%",
                    "innerRadius": "40%",
                    "labelText": "[[title]]",
                    "export": {
                        "enabled": false
                    }
                } );
            });
        };

        $scope.getComments = function (zeile, today) {
            if ($scope.comments[zeile.kunde]) {
                var comments = _.filter($scope.comments[zeile.kunde], function (row) { return (today === '1') ? row.datum === zeile.datum : row.datum <= zeile.datum; });

                if (zeile.fehlend === '1') {
                    return comments;
                }
                if (zeile.bearbeitet === '0') {
                    var lastErrorComments = _.filter(comments, function (row) { return row.status > 0; });
                    if (lastErrorComments.length > 0) {
                        return lastErrorComments;
                    }
                }
                var newComments = _.filter(comments, function (row) { return row.datum === zeile.datum; });
                if (newComments.length > 0) {
                    return newComments;
                }
            }
            return false;
        };

        $scope.getCommentsInfo = function (comment_id) {
            if ($scope.comments2[comment_id] !== undefined) {
                var c = $scope.comments2[comment_id];
                return '<i>' + $scope.domain.bearbeitet[c.status] + '</i><br/>' + c.kommentar;
            }
            return 'blubb';
        };

        $scope.getCommentIcon = function (c) {
            var c0 = c;
            if (c.length > 0) {
                c0 = c[0];
            }
            if (c0.status) {
                return $scope.domain.comment[c0.status];
            }
            return "glyphicon-question-sign";
        };


        $scope.shortFilename = function(filename) {
            if (filename !== undefined && filename.length > 0 && filename.indexOf("\\") >= 0) {
                return filename.substring(filename.lastIndexOf("\\") + 1);
            }
            return filename;
        };

        $scope.showDetails = function (entry) {
            $scope.current.details = entry;

            var duration = _.map(_.filter(entry.Sources, function(e) { return e.Duration > '00:01:00'; }), function(e) { return { 'title': $scope.shortFilename(e.Filename) + ' (' + e.Duration + ')', 'value':  Math.round(moment.duration(e.Duration, 'HH:mm:ss').asMinutes()) }; });

            var chart = AmCharts.makeChart( "durationDetailsChart", {
                "type": "pie",
                "theme": "light",
                "dataProvider": duration,
                "titleField": "title",
                "valueField": "value",
                "labelRadius": 5,
                "radius": "42%",
                "innerRadius": "50%",
                "labelText": "[[title]]",
                "export": {
                    "enabled": false
                }
            } );
        };

        $scope.saveUser = function (name) {
            window.localStorage.setItem("Benutzer", name);
            $scope.benutzer = name;
        };

        $scope.saveComments = function () {
            $http.put(webservice + 'a=kommentar&id=' + $scope.current.kommentar.id, $scope.current.kommentar).success(function (data) {
                $scope.comments = _.groupBy(data, 'kunde');

                if ($scope.current.kommentar.id === '') {
                    $scope.refresh();
                }
            });
        };

        $scope.saveStartTime = function (zeile) {
            $http.put(webservice + 'a=zeit&kunde=' + zeile.kunde + '&start_soll=' + zeile.start + '&ende_soll=' + zeile.ende_soll).success(function (data) {
                zeile.start_soll = zeile.start;
            });
        };

        $scope.saveEndTime = function (zeile) {
            $http.put(webservice + 'a=zeit&kunde=' + zeile.kunde + '&start_soll=' + zeile.start_soll + '&ende_soll=' + zeile.ende).success(function (data) {
                zeile.ende_soll = zeile.ende;
            });
        };

        $scope.statusFilter = function (row) {
            return (row.status >= $scope.current.status || row.datum === $scope.current.zeile.datum);
        };

        $scope.editComment = function (c) {
            c.fehler = parseInt(c.fehler, 10);
            $scope.current.kommentar = c;
        };

        $scope.whitelistToggle = function (key, value) {
            var flag = (!$scope.inWhitelist(key, value)) ? "J" : "N";
            $http.put(webservice + 'a=whitelist&kunde=' + $scope.current.zeile.kunde + '&typ=' + key + '&wert=' + value + "&aktiv=" + flag).success(function (data) {
                if (data.whitelist !== undefined) {
                    $scope.current.fehler.whitelist = data.whitelist;
                }
            });
        };

        $scope.inWhitelist = function (key, value) {
            return $scope.current.fehler.whitelist[key] !== undefined && _.contains($scope.current.fehler.whitelist[key], value);
        };
    });