var window_location = window.location.pathname

var nestene = angular.module('nestene', ['JSONedit']);

nestene.service('AutonTypes', function($http, $q) {

this.types = $http.get(window_location + 'auton_types');

});

nestene.controller('AutonsController', function($scope, $http, $timeout) {

$scope.autons=[];

$scope.getAutons = function() {
  var autonsPromise = $http.get(window_location + "autons.json");
  autonsPromise.success(function(data, status, headers, config) {
    $scope.autons = data;
  });

  autonsPromise.error(function(data, status, headers, config) {
    $.bootstrapGrowl("getting autons failed!", { type: 'danger' });
  });
}

$scope.getAutons();
$scope.intervalFunction = function() {
  $timeout(function() {
    $scope.getAutons();
    $scope.intervalFunction();
  }, 60000);
};

$scope.intervalFunction();

});

nestene.controller('CreateAutonFormController', function($scope,$http, AutonTypes) {

$scope.autonType = '';
$scope.createAuton = function() {
  var postPromise = $http.post(window_location + "autons",{auton_type: $scope.autonType});
  postPromise.success(function(data, status, headers, config) {
    $.bootstrapGrowl("Created "+data['auton_id'], { type: 'success' });
  });
  postPromise.error(function(data, status, headers, config) {
    $.bootstrapGrowl("Could not create Auton: "+data['message'], { type: 'error' });
  });
};
$scope.auton_types = [];
AutonTypes.types.success(function(data, status, headers, config) {
  console.log('auton_types:' + data);
  $scope.auton_types = data;
});

});

nestene.controller('CredentialsController', function($scope,$http) {

$scope.credentials={};
$scope.loaded = false;

$scope.loadCredentials = function() {
  var getPromise = $http.get(window_location + "credentials");
  getPromise.success(function(data, status, headers, config) {
    $scope.credentials = data;
    $scope.loaded = true;
  });

  getPromise.error(function(data, status, headers, config) {
    $.bootstrapGrowl("getting credentials failed!", { type: 'danger' });
  });
}

$scope.loadCredentials();

$scope.storeCredentials = function() {
  var postPromise = $http.post(window_location + "credentials",$scope.credentials);
  postPromise.success(function(data, status, headers, config) {
    $.bootstrapGrowl("Credentials saved", { type: 'success' });
  });
  postPromise.error(function(data, status, headers, config) {
    $.bootstrapGrowl("Could not save credentials", { type: 'danger' });
  });
};

});