angular
    .module('universal')
    .controller('RulesController', function ($scope, $http, $window, Upload) {

        $scope.sources = [];
        $scope.objects = [];
        $scope.rules = [];

        $scope.problems = [];
        $scope.problemsObjects = [];

        $scope.Message = {
            Text: '',
            Visible: false
        };

        $scope.uploadFiles = function (files, errFiles) {

            $scope.errFiles = errFiles;
            angular.forEach(files, function (file) {
                file.upload = Upload.upload({
                    url: '/rules/add/',
                    data: { file: file }
                });

                file.upload.then(function (response) {
                    $window.location.reload();
                }, function (response) {
                    if (response.status > 0)
                        $scope.errorMsg = response.status + ': ' + response.data;
                }, function (evt) {
                    file.progress = Math.min(100, parseInt(100.0 *
                        evt.loaded / evt.total));
                });
            });
        }

        $scope.addSearchTemplate = function () {
            console.log('yep!');
        };

        // при изменении ссылки на документорий на странице редактирования конфига
        $scope.changeDocumentory = function (id, documentory) {
            $http({
                method: "POST",
                url: '/ruleconfigs/changeDocumentory/' + id,
                data: $.param({
                    Documentory: documentory
                }),
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).then(function (response) {
                if (response.data.result) {

                } else {
                    alert("Не удалось сохранить ссылку на документорий")
                    window.location.reload()
                }
            }, function () {
                alert("Не удалось сохранить ссылку на документорий")
                window.location.reload()
            })
        }

        //Sources
        //$scope.initSource = function (listname, id) {
        //    $scope.objects[listname] = {};
        //    $scope.objects[listname].selectedSource = {};
        //    $scope.objects[listname].selectedSource.ObjectID = id;
        //};

        $scope.getSources = function () {
            $http.post('/sources/GetAllSources/').then(function (response) {
                $scope.sources = response.data.Sources;
            });
        };

        //Problems
        $scope.initProblem = function (itemId, problemId) {
            $scope.problemsObjects[itemId] = {};
            $scope.problemsObjects[itemId].selectedProblem = {};
            $scope.problemsObjects[itemId].selectedProblem.ID = problemId;
        };

        $scope.getProblems = function () {
            $http.post('/sources/GetAllProblems/').then(function (response) {
                $scope.problems = response.data.Problems;
            });
        };

        $scope.setProblem = function (configEntityTypeId, problemId) {

            $.post(
                '/sources/setProblem/',
                {
                    configEntityTypeId: configEntityTypeId,
                    problemId: problemId
                },
                function (data) {
                    console.log(data);
                });

            //$http.post('/sources/setProblem/', { configEntityTypeId: configEntityTypeId, problemId: problemId }).then(function (response) {
            //    $scope.problems = response.data.Problems;
            //});
        }

        $scope.uploadConfig = function (files, errFiles, ruleConfigID) {

            $scope.errFiles = errFiles;
            angular.forEach(files, function (file) {
                file.upload = Upload.upload({
                    url: '/config/update/',
                    data: {
                        file: file,
                        id: ruleConfigID
                    }
                });

                file.upload.then(function (response) {
                    if (response.data.result === 'error') {
                        $scope.showMessage(response.data);
                    }
                    else
                        $window.location.reload();
                }, function (response) {
                    if (response.status > 0)
                        $scope.errorMsg = response.status + ': ' + response.data;
                }, function (evt) {
                    file.progress = Math.min(100, parseInt(100.0 *
                        evt.loaded / evt.total));
                });
            });
        }

        $scope.unloadConfig = function (ruleConfigID) {
            window.location.href = "/config/unloadConfig/" + ruleConfigID;
        }

        $scope.showMessage = function (data) {
            $scope.Message.Visible = true;
            $scope.Message.Text = data.warningText;
        }

        $scope.getVersions = function (id) {
            $http.get('/rules/GetVersions/' + encodeURIComponent(id)).then(function (response) {
                $scope.rules = response.data;
            })
        }

        $scope.getMigrationChanges = function (newRuleID, oldRuleID) {
            $.get('/rules/GetMigrationChanges/',
                {
                    oldRuleID: oldRuleID,
                    newRuleID: newRuleID
                }, function (response) {
                    $scope.$apply(function () {
                        $scope.migrationChanges = response;
                    });
                });
        };

        $scope.applyMigration = function (processID, oldRuleConfigID, newRuleID, oldRuleID) {
            $.post('/rules/ApplyMigration/',
                {
                    processID: processID,
                    oldRuleConfigID: oldRuleConfigID,
                    newRuleID: newRuleID,
                    oldRuleID: oldRuleID

                }, function (response) {
                    $scope.$apply(function () {
                        $scope.migrationChanges = response;
                    });
                });
        };

        $scope.getSources();
        $scope.getProblems();
    })