backupApp.directive('backupImportTask', function (gettextCatalog) {
    return {
        restrict: 'E',
        scope: {
            importBackup: '=importBackup',
            onComplete: '&',
        },
        templateUrl: 'templates/backups/import/backup-import-task.html?v=1.1.1.2',
        controller: function ($scope, AppService, ServerStatus) {
            $scope.ConnectingServer = true;

            $scope.task = {
                Name: $scope.importBackup.Backup.Name,
                ID: null,
                isComplete: false,
                Errors: []
            }

            AppService.post('/backups/import', $scope.importBackup, { 'headers': { 'Content-Type': 'application/json' } })
            .then(function(response) {
                const task = response.data;
                if (task.isSuccess) {
                    if (task.ID == 0)
                    {
                        $scope.isComplete = $scope.task.isComplete = true;
                        $scope.onComplete();
                    }
                    else {
                        $scope.task.ID = task.ID;
                        
                        ServerStatus.callWhenTaskCompletes(task.ID, function() {
                            setTimeout(() => {
                                $scope.isComplete = $scope.task.isComplete = true;
                                $scope.onComplete();
                                $scope.$digest();
                            }, 500)
                        });
                    }
                }
                else {
                    $scope.task.Errors = task.Errors
                    $scope.isComplete = task.isComplete = true;
                    $scope.onComplete();

                }
                $scope.ConnectingServer = false;

            }, function() {
                $scope.task.Errors.push({Property: '', Error: 'Server returned an unexpected error.' })
                $scope.ConnectingServer = false;
                $scope.isComplete = task.isComplete = true;
            });
        }
    };
});