backupApp.directive('waitArea', function() {
  return {
    restrict: 'E',
    scope: {
        taskid: '=taskid',
        text: '=text',
        allowCancel: '=allowCancel'
    },
    templateUrl: 'templates/waitarea.html?v=1.1.1.1',
    controller: function($scope, ServerStatus, AppService) {
        $scope.ServerStatus = ServerStatus;

        function updateState()
        {
          if ($scope.Serverstate.activeTask == null || $scope.Serverstate.activeTask.Item1 != $scope.taskid)
          {
            if ($scope.Serverstate.lastPgEvent && $scope.Serverstate.lastPgEvent.TaskID == $scope.taskid)
            {
              $scope.state.text = ServerStatus.progress_state_text[$scope.Serverstate.lastPgEvent.Phase] || $scope.Serverstate.lastPgEvent.Phase;
              $scope.state.progress = $scope.Serverstate.lastPgEvent.OverallProgress;
            }
          }
          else if ($scope.Serverstate.programState == 'Paused')
          {
            $scope.state.phase = 'paused';
          }
          else {
            $scope.state.phase = 'running';
            if ($scope.Serverstate.lastPgEvent && $scope.Serverstate.lastPgEvent.TaskID == $scope.taskid) {
              $scope.state.text = ServerStatus.progress_state_text[$scope.Serverstate.lastPgEvent.Phase] || $scope.Serverstate.lastPgEvent.Phase;
              $scope.state.progress = $scope.Serverstate.lastPgEvent.OverallProgress;
            }
          }
        }


        $scope.state = {
          phase: 'waiting',
          text: '',
          progress: 0
        }

        $scope.Serverstate = ServerStatus.watch($scope, () => updateState());
        $scope.$watch('Serverstate.lastPgEvent', updateState);

        $scope.cancelTask = function() {
            AppService.post('/task/' + $scope.taskid + '/abort');
        };
    }
  }
});
