'use strict';

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

        $scope.current = {
            'kunde': $routeParams.customer,
            'datum': $routeParams.date,
			'tabelle': ''
        };

        $scope.data = {};
        $scope.domain = {};
        $scope.filter = {};

        $scope.options = {
            'kunde': [],
            'datum': {}
        };

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

        $scope.emails = function () {
            if ($scope.domain !== undefined && $scope.domain.versand !== undefined && $scope.domain.versand.Empfaenger !== undefined) {
                return $scope.domain.versand.Empfaenger.join('\r\n');
            }
            return "";
        };
		
        $scope.csvExport = function () {
			var file = new File([ $scope.getCsv() ], $scope.current.kunde + "_" + $scope.current.tabelle + ".csv", {type: "text/plain;charset=iso-8859-1"});
			saveAs(file);
            return "";
        };
		
		$scope.getCsv = function () {
			var result = _.keys($scope.data[$scope.current.tabelle][0]).join(';').replace('$$hashKey','Nr.') + '\r\n';
			_.each($scope.data[$scope.current.tabelle], function (row, i) { 
				_.each(row, function (col, k) {
					if (k !== '$$hashKey') {
						result += col + ';'; 
					} else {
						result += (i+1);
					}
				});
				result += '\r\n';
			});
			return result;
		};
		
		
        $scope.refresh = function () {
            $scope.data = {};
            $http.get(webservice + 'a=config&kunde=' + $scope.current.kunde + '&datum=' + $scope.current.datum).success(function (data) {
                $scope.options.datum = data.options;
                $scope.options.datum[undefined] = [];
                $scope.options.kunde = _.keys(data.options);
                if (data.current) {
                    $scope.current.datum = data.current.datum;
                    $scope.options.tabelle = _.keys(data.current.info);
                    $scope.current.tabelle = _.first($scope.options.tabelle);
                    $scope.data = data.current.info;

                    _.each($scope.data, function (table, t) {
                        $scope.domain[t] = {};
                        $scope.filter[t] = {};
                        _.each(table[0], function (col, k) {
                            $scope.domain[t][k] = _.uniq(_.pluck(table, k));
                            $scope.domain[t][k].sort();
                            $scope.filter[t][k] = '';
                        });
                    });

                }
                $scope.options.datum[undefined] = [];
            });
        };

        $scope.refresh();
    });