angular.module('tasks').controller('MainCtrl', function ($scope, $http, $interval, $timeout, $window) {
    var webservice = 'api/';
    var firstLine = '@call "%~dp0"scripts\\config.bat 0 > nul\r\n';

    $scope.options = {};
    $scope.jobname = "remote_" + moment().format('YYYY-MM-DD_HHmm') + ".bat";
    $scope.statusmail = false;
    $scope.logfile = "";
    $scope.protocol = "";
    $scope.style = "default";

    $scope.pcvisit = { 'Number': "12345678" };

    $scope.selected = {
        'Tasks': [],
        'Starter': [],
        'Transformer': [],
        'Impromptu': [],
        'Powerplay': [],
        'Portal': [],
        'Logs': []
    };

    $scope.preselected = {
        'Tasks': [],
        'Starter': [],
        'Transformer': [],
        'Impromptu': [],
        'Powerplay': [],
        'Portal': []
    };

    $scope.details = {
        'Tasks': {},
        'Starter': {},
        'Transformer': {},
        'Impromptu': {},
        'Powerplay': {},
        'Portal': {}
    };

    $http.get(webservice + '?action=options').success(function (data) {
        $scope.options = data;
    });

    $scope.newEntry = function (type) {
        switch (type) {
        case 'Tasks':
            return function (v) {
                return {
                    'Name': v,
                    'komplett': true,
                    'Auswahl': [],
                    'Befehle': [],
                    'toString': function () {
                        if (this.komplett !== true) {
                            var b = "", befehle = $scope.batchFilter($scope.details.Tasks[v].contents);
                            _.each(this.Auswahl, function (value, i) {
                                if (value && befehle[i] !== undefined) {
                                    b += befehle[i] + '\r\n';
                                }
                            });
                            return b;
                        }
                        return 'call ..\\' + this.Name + '\r\n';
                    }
                };
            };
        case 'Starter':
            return function (v) {
                return {
                    'Name': v,
                    'toString': function () {
                        return 'call %STARTER%\\Batch\\' + this.Name + '\r\n' + 'cd /d "%~dp0"scripts\r\n';
                    }
                };
            };
        case 'Transformer':
            return function (v) {
                return {
                    'Name': v,
                    'Anzahl': 1,
                    'toString': function () {
                        return 'call transformer.bat ' + this.Name + ' ' + this.Anzahl + '\r\n';
                    }
                };
            };
        case 'Impromptu':
            return function (v) {
                return {
                    'Name': v,
                    'iqd': false,
                    'ims': false,
                    'csv': false,
                    'toString': function () {
                        var result = '';
                        if (this.iqd) {
                            result += 'call impromptu.bat ' + this.Name + ' iqd\r\n';
                        }
                        if (this.ims) {
                            result += 'call impromptu.bat ' + this.Name + ' ims\r\n';
                        }
                        if (this.csv) {
                            result += 'call impromptu.bat ' + this.Name + ' csv\r\n';
                        }
                        return result;
                    }
                };
            };
        case 'Powerplay':
            return function (v) {
                return {
                    'Name': v,
                    'ppx': false,
                    'gif': false,
                    'pdf': false,
                    'csv': false,
                    'xls': false,
                    'toString': function () {
                        var result = '';
                        if (this.ppx) {
                            result += 'call powerplay.bat %PORTAL%\\System\\Report\\' + this.Name + ' ppx\r\n';
                        }
                        if (this.gif) {
                            result += 'call powerplay.bat %PORTAL%\\System\\Report\\' + this.Name + ' gif\r\n';
                        }
                        if (this.pdf) {
                            result += 'call powerplay.bat %PORTAL%\\System\\Report\\' + this.Name + ' pdf\r\n';
                        }
                        if (this.csv) {
                            result += 'call powerplay.bat %PORTAL%\\System\\Report\\' + this.Name + ' csv\r\n';
                        }
                        if (this.xls) {
                            result += 'call powerplay.bat %PORTAL%\\System\\Report\\' + this.Name + ' xls\r\n';
                        }
                        return result;
                    }
                };
            };
        default:
            return function (v) {
                return {
                    'Name': v,
                    'Benutzer': "*",
                    'Struktur': "*",
                    'Cubes': "*",
                    'toString': function () {
                        return 'call generate.bat ' + this.Name + ' "' + this.Benutzer + '" "' + this.Cubes + '" "' + this.Struktur + '"\r\n';
                    }
                };
            };
        }
    };

    $scope.add = function (type) {
        $scope.selected[type] = _.union($scope.selected[type], _.map($scope.preselected[type], $scope.newEntry(type)));

        $http.post(webservice + '?action=details&params=' + type, { 'files': $scope.preselected[type] }).success(function (data) {
            $scope.details[type] = _.extend($scope.details[type], data);
        });

        $scope.preselected[type] = [];
    };

    $scope.remove = function (type, element) {
        $scope.selected[type] = _.without($scope.selected[type], element);
    };

    $scope.runJob = function () {
        var job = firstLine;

        _.each($scope.selected, function (sel, type) {
            _.each(sel, function (e) {
                job += e.toString();
            });
        });

        if ($scope.statusmail) {
            job += "call fehlermeldung.bat " + $scope.jobname + "\r\n";
        }
        job += "echo (.)\r\n";
        job += "del /F %TASKS%\\" + $scope.jobname;

        $http.post(webservice + '?action=batch&params=' + $scope.jobname, { 'job': job }).success(function (data) {
            if (data !== $scope.jobname) {
                $scope.protocol = data;
            } else {
                $scope.protocol = "Der Prozess wird gestartet...";
            }
            $scope.logfile = data + ".log";
            $scope.getLogfile();
        });
    };

    $scope.pcvisitConnect = function () {
        $http.post(webservice + '?action=batch&params=pcv.bat', { 'job': firstLine + 'call pcvisit.bat ' + $scope.pcvisit.Number + '\r\n' }).success(function (data) {
            $scope.pcvisit.Number = "";
        });
    };

    $scope.refresh = function () {
        $http.get(webservice + '?action=logs&params=' + $scope.logfile).success(function (data) {
            $scope.protocol = data;

            if (data.indexOf('(.)') > -1) {
                $scope.protocol = data.substring(0, data.indexOf('(.)'));
                $interval.cancel();
                $scope.style = "bg-success";

                if (data.indexOf('Fehler') > -1 || data.indexOf('(TR') > -1) {
                    $scope.style = "bg-danger";
                }
            }

            $timeout(function () {
                $window.scrollTo(0, $window.document.body.clientHeight);
            }, 1000);
        });
    };

    $scope.getLogfile = function () {
        $scope.style = "bg-warning";
        // $scope.refresh();
        $interval($scope.refresh, 20000);
    };

    $scope.stopAndTop = function () {
        $interval.cancel();
        $window.scrollTo(0, 0);
    };

    $scope.batchFilter = function (batch) {
        return _.filter(batch, function (row) {
            return (row.indexOf('@call "%~dp0"') < 0 && row.indexOf('call') > -1);
        });
    };

});