<commit_before>/*global log: false */

log.write('controllers.js');

var html5AppId = '3C4ECBD1-7CC2-4A1B-B90B-6B4AB000A459',
    ugBaseUrl = 'https://api.usergrid.com/dino/loadgen1', 
    jobsUrl = ugBaseUrl + '/jobs', 
    loadgenUrl = 'http://lvh.me:8001';
    //jobsUrl = loadgenUrl + '/jobs';


log.write('ugBaseUrl: ' + ugBaseUrl);

function Job(name, desc, defaultProps) {
  return {
    type        : "job", 
    name        : name, 
    description : desc, 
    defaultProperties: defaultProps
  };
}

function MainController ($scope, $http, $dialog, $q /*, $httpProvider , $compile */ ) {
  var dialogModel = {}, token, reUrl = new RegExp('https?://[^/]+(/.*)$'), 
      httpConfig, initialContext = {};

  $scope.sortKey = 'created';
  $scope.sortReverse = false;
  $scope.jobRecords = [];
  $scope.securityContext = {};
  $scope.showDetails = [];

  $scope.loginRegisterDialogOpts = {
    backdrop: true,
    keyboard: true,
    backdropClick: false,
    templateUrl: 'views/login-register-dialog.htm',
    controller: 'LoginRegisterDialogController',
    // resolve is used to inject data into the controller for the dialog.
    resolve: {
      dialogModel: function() { return angular.copy(dialogModel); },
      wantIdentity: function() { return true; },
      title: function() { return "unkown"; }}
  };


  $scope.initialContextDialogOpts = {
    backdrop: true,
    keyboard: true,
    backdropClick: false,
    templateUrl: 'views/initial-context-dialog.htm',
    controller: 'InitialContextDialogController',
    // resolve is used to inject data into the controller for the dialog.
    resolve: {
      initialContext: function() { return angular.copy(initialContext); },
      title: function() { return 'Initial Context'; }
    }
  };


  log.write('MainController');
  // check for existing, working token
  token = window.localStorage.getItem(html5AppId + '.bearerToken');
  if (token) {
    // verify that the token is valid, not expired
    log.write('checking OAuth token: ' + token);
    httpConfig = { headers:{ 'Authorization': 'Bearer ' + token, 'Accept': 'application/json'} };
    $http.get(loadgenUrl + '/users/me', httpConfig)
      .success(function ( response ) {
        // success implies the token is valid
        $scope.securityContext = { access_token : token, user: response.entities[0]};
        log.write('OAuth token: ' + $scope.securityContext.access_token);
        log.write('user uuid: ' + $scope.securityContext.user.uuid);
        $http.defaults.headers.common.Authorization = 'Bearer ' + $scope.securityContext.access_token;
        initialRetrieve();
      })
      .error(function(data, status, headers, config) {
        // in case of error, the token is probably stale.
        log.write('OAuth token validation failed');
        log.write('data: ' + JSON.stringify(data, null, 2));
        window.localStorage.removeItem(html5AppId + '.bearerToken');
        $scope.securityContext.checked = true;
      });
  }
  else {
    log.write('no cached OAuth token.');
    $scope.securityContext.checked = true;
  }

  $scope.openRegisterDialog = function() {
    dialogModel = {};
    $scope.loginRegisterDialogOpts.resolve.title = function() { return "Register"; };
    $scope.loginRegisterDialogOpts.resolve.wantIdentity = function() { return true; };
    var d = $dialog.dialog($scope.loginRegisterDialogOpts);
    d.open().then(function(result){
      if(result) {
        register(result);
      }
    });
  };

  $scope.openLoginDialog = function(keepErrorMsg) {
    if ( ! keepErrorMsg && dialogModel.errorMessage) { delete dialogModel.errorMessage; }
    $scope.loginRegisterDialogOpts.resolve.title = function() { return 'Login'; };
    $scope.loginRegisterDialogOpts.resolve.wantIdentity = function() { return false; };
    var d = $dialog.dialog($scope.loginRegisterDialogOpts);
    d.open().then(function(result){
      if(result) {
        login(result, initialRetrieve);
      }
    });
  };

  $scope.toggleJobStatus = function(item, $event) {
    if (item.status == 'running') {
      $scope.stopJob(item, $event);
    }
    else {
      $scope.openInitialContextDialog(item, $event);
    }
  };

  $scope.openInitialContextDialog = function(item, $event) {
    $scope.initialContextDialogOpts.resolve.title = function() { 
      return 'Initial Context: ' + item.name; 
    };
    var d = $dialog.dialog($scope.initialContextDialogOpts);
    d.open().then(function(result){
      if(result && result.payload) {
        $scope.startJob(item, result.payload); 
      }
    });
  };

  $scope.startJob = function (job, payload) {
    //   POST /jobs/{job-id}?action=start
    $http.post(loadgenUrl + '/jobs/' + job.uuid + '?action=start', payload)
      .success(function(data) {
        log.write('start: ' + JSON.stringify(data));
        job.status = 'running';
      })
      .error(function(data, status, headers, config) {
        log.write('start failed...' + JSON.stringify(data));
      });
  };

  $scope.stopJob = function (job, $event) {
    //   POST /jobs/{job-id}?action=stop
    $http.post(loadgenUrl + '/jobs/' + job.uuid + '?action=stop')
      .success(function(data) {
        log.write('stop: ' + JSON.stringify(data));
        job.status = 'stopped';
      })
      .error(function(data, status, headers, config) {
        log.write('stop failed...' + JSON.stringify(data));
      });
  };

  $scope.getJobCssClass = function (job) {
    if (job.status === 'running') { return 'icon-stop';}
    return 'icon-play';
  };

  $scope.logout = function() {
    log.write('signing out user ' + $scope.securityContext.user.uuid);
    delete $http.defaults.headers.common.Authorization;
    window.localStorage.removeItem(html5AppId + '.bearerToken');
    $scope.jobRecords = [];
    $scope.securityContext = { checked : true }; // checked and not authenticated
  };

  // see http://docs.angularjs.org/api/ng.$http
  // after login:
  // $httpProvider.defaults.headers.common['Authorization'] = 'Bearer ' + access_token;
<commit_msg>Mark job as stopped when stop fails because it is not running.<commit_after>/*global log: false */

log.write('controllers.js');

var html5AppId = '3C4ECBD1-7CC2-4A1B-B90B-6B4AB000A459',
    ugBaseUrl = 'https://api.usergrid.com/dino/loadgen1', 
    jobsUrl = ugBaseUrl + '/jobs', 
    loadgenUrl = 'http://lvh.me:8001';
    //jobsUrl = loadgenUrl + '/jobs';


log.write('ugBaseUrl: ' + ugBaseUrl);

function Job(name, desc, defaultProps) {
  return {
    type        : "job", 
    name        : name, 
    description : desc, 
    defaultProperties: defaultProps
  };
}

function MainController ($scope, $http, $dialog, $q /*, $httpProvider , $compile */ ) {
  var dialogModel = {}, token, reUrl = new RegExp('https?://[^/]+(/.*)$'), 
      httpConfig, initialContext = {};

  $scope.sortKey = 'created';
  $scope.sortReverse = false;
  $scope.jobRecords = [];
  $scope.securityContext = {};
  $scope.showDetails = [];

  $scope.loginRegisterDialogOpts = {
    backdrop: true,
    keyboard: true,
    backdropClick: false,
    templateUrl: 'views/login-register-dialog.htm',
    controller: 'LoginRegisterDialogController',
    // resolve is used to inject data into the controller for the dialog.
    resolve: {
      dialogModel: function() { return angular.copy(dialogModel); },
      wantIdentity: function() { return true; },
      title: function() { return "unkown"; }}
  };


  $scope.initialContextDialogOpts = {
    backdrop: true,
    keyboard: true,
    backdropClick: false,
    templateUrl: 'views/initial-context-dialog.htm',
    controller: 'InitialContextDialogController',
    // resolve is used to inject data into the controller for the dialog.
    resolve: {
      initialContext: function() { return angular.copy(initialContext); },
      title: function() { return 'Initial Context'; }
    }
  };


  log.write('MainController');
  // check for existing, working token
  token = window.localStorage.getItem(html5AppId + '.bearerToken');
  if (token) {
    // verify that the token is valid, not expired
    log.write('checking OAuth token: ' + token);
    httpConfig = { headers:{ 'Authorization': 'Bearer ' + token, 'Accept': 'application/json'} };
    $http.get(loadgenUrl + '/users/me', httpConfig)
      .success(function ( response ) {
        // success implies the token is valid
        $scope.securityContext = { access_token : token, user: response.entities[0]};
        log.write('OAuth token: ' + $scope.securityContext.access_token);
        log.write('user uuid: ' + $scope.securityContext.user.uuid);
        $http.defaults.headers.common.Authorization = 'Bearer ' + $scope.securityContext.access_token;
        initialRetrieve();
      })
      .error(function(data, status, headers, config) {
        // in case of error, the token is probably stale.
        log.write('OAuth token validation failed');
        log.write('data: ' + JSON.stringify(data, null, 2));
        window.localStorage.removeItem(html5AppId + '.bearerToken');
        $scope.securityContext.checked = true;
      });
  }
  else {
    log.write('no cached OAuth token.');
    $scope.securityContext.checked = true;
  }

  $scope.openRegisterDialog = function() {
    dialogModel = {};
    $scope.loginRegisterDialogOpts.resolve.title = function() { return "Register"; };
    $scope.loginRegisterDialogOpts.resolve.wantIdentity = function() { return true; };
    var d = $dialog.dialog($scope.loginRegisterDialogOpts);
    d.open().then(function(result){
      if(result) {
        register(result);
      }
    });
  };

  $scope.openLoginDialog = function(keepErrorMsg) {
    if ( ! keepErrorMsg && dialogModel.errorMessage) { delete dialogModel.errorMessage; }
    $scope.loginRegisterDialogOpts.resolve.title = function() { return 'Login'; };
    $scope.loginRegisterDialogOpts.resolve.wantIdentity = function() { return false; };
    var d = $dialog.dialog($scope.loginRegisterDialogOpts);
    d.open().then(function(result){
      if(result) {
        login(result, initialRetrieve);
      }
    });
  };

  $scope.toggleJobStatus = function(item, $event) {
    if (item.status == 'running') {
      $scope.stopJob(item, $event);
    }
    else {
      $scope.openInitialContextDialog(item, $event);
    }
  };

  $scope.openInitialContextDialog = function(item, $event) {
    $scope.initialContextDialogOpts.resolve.title = function() { 
      return 'Initial Context: ' + item.name; 
    };
    var d = $dialog.dialog($scope.initialContextDialogOpts);
    d.open().then(function(result){
      if(result && result.payload) {
        $scope.startJob(item, result.payload); 
      }
    });
  };

  $scope.startJob = function (job, payload) {
    //   POST /jobs/{job-id}?action=start
    $http.post(loadgenUrl + '/jobs/' + job.uuid + '?action=start', payload)
      .success(function(data) {
        log.write('start: ' + JSON.stringify(data));
        job.status = 'running';
      })
      .error(function(data, status, headers, config) {
        log.write('start failed...' + JSON.stringify(data));
      });
  };

  $scope.stopJob = function (job, $event) {
    //   POST /jobs/{job-id}?action=stop
    $http.post(loadgenUrl + '/jobs/' + job.uuid + '?action=stop')
      .success(function(data) {
        log.write('stop: ' + JSON.stringify(data));
        job.status = 'stopped';
      })
      .error(function(data, status, headers, config) {
        log.write('stop failed...' + JSON.stringify(data));
        if (data.message == "that job is not currently running") {
          job.status = 'stopped';
        }
      });
  };

  $scope.getJobCssClass = function (job) {
    if (job.status === 'running') { return 'icon-stop';}
    return 'icon-play';
  };

  $scope.logout = function() {
    log.write('signing out user ' + $scope.securityContext.user.uuid);
    delete $http.defaults.headers.common.Authorization;
    window.localStorage.removeItem(html5AppId + '.bearerToken');
    $scope.jobRecords = [];
    $scope.securityContext = { checked : true }; // checked and not authenticated
  };

  // see http://docs.angularjs.org/api/ng.$http
  // after login:
  // $httpProvider.defaults.headers.common['Authorization'] = 'Bearer ' + access_token;

{'fraction_non_alphanumeric': 0.155706789111184, 'fraction_numerical': 0.0045916693998032145, 'mean_word_length': 3.0806289729006355, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7109868', 'n_tokens_mistral': 3782, 'n_tokens_neox': 3707, 'n_words': 739}