koerseadmin/js/controllers.js

737 lines
21 KiB
JavaScript

'use strict';
/* Controllers */
var mod = angular.module('bananaraceApp.controllers', ['bananaraceApp.services']);
mod.controller('BodyCtrl', ['$scope', 'StopwatchService', 'LoginService', function($scope, StopwatchService, LoginService) {
console.log('body controller loaded?');
$scope.name = 'World';
$scope.keyCode = "";
$scope.keyPressed = function(e) {
console.log('KEY PRESSED');
$scope.keyCode = e.which;
};
$scope.isLoggedIn = function() {
return LoginService.isLoggedIn();
}
}]);
// STOPWATCH CONTROLLER
mod.controller('StopwatchCtrl', ['$scope', 'StopwatchService', 'TemplateBackendService', 'hotkeys', function($scope, StopwatchService, TemplateBackendService, hotkeys) {
//set the interval in ms to 0ms
$scope.intervalValue = StopwatchService.getValue();
//set the current templates: this can be refreshed when necessary. initialise with first call.
$scope.templates = refreshTemplates();
//keep image of the current lefas here... update when necessary!
$scope.currentTemplateItems = StopwatchService.getCurrentTemplateItems();
$scope.templateItemIndex = StopwatchService.currentlyRunningTemplateItemIndex();
//get the current time
var stopwatchUpdateTimer;
hotkeys.add({
combo: 'space',
description: 'Tap to function... press space!',
callback: function(event, hotkey) {
console.log('pressed space');
$scope.tap();
event.preventDefault();
}
});
//keep track of leafs
//leaf1 - leaf2 - leaf3 - ...
//overall timer
//leaf timer
//events (taps)
//start sequence
//end leaf1 (add timing)
//end leaf2 (add timing)
//final leaf done? end sequence -> save timings
$scope.getCurrentStopwatchValue = function() {
return StopwatchService.getValue();
};
$scope.readyForTapping = function() {
var currentTemplate = StopwatchService.getActiveTemplate();
var ready = currentTemplate != null;
return ready;
};
$scope.getActiveTemplate = function() {
return StopwatchService.getActiveTemplate();
}
$scope.tap = function() {
if(StopwatchService.isRunning()===false) {
//start refreshing timer!
stopwatchUpdateTimer = setInterval(
function () {
fireStopwatchTimer();
}, 10);
}
//now tap the thing
StopwatchService.tap();
$scope.templateItemIndex = StopwatchService.currentlyRunningTemplateItemIndex();
//if, after the tap, the timer isn't running: we stopped! stop listening
if(StopwatchService.isRunning()===false) {
console.log('clearing timeout!');
clearTimeout(stopwatchUpdateTimer);
//save the timings!?
//make assoc array for the timings
var currentTemplateItems = StopwatchService.getCurrentTemplateItems();
var currentTemplateid = StopwatchService.getActiveTemplate().idtemplate;
//just push them all to the database: everything is filled in
//save it to db
TemplateBackendService.saveTiming(currentTemplateid, currentTemplateItems).
success(function(data, status, headers, config) {
console.log('saveTiming call successfull...');
if(data['ok']==true) {
$scope.refreshTimings();
} else {
console.log('timing wasnt saved');
}
console.log(data);
}).
error(function(data, status, headers, config) {
console.log('saveTiming call failed...');
console.log(data);
});
};
};
$scope.cancel = function() {
StopwatchService.cancel();
clearTimeout(stopwatchUpdateTimer);
};
$scope.isTimerRunning = function() {
return StopwatchService.isRunning();
};
$scope.refreshTimings = function() {
console.log('HI refreshing timings');
TemplateBackendService.getTimings(StopwatchService.getActiveTemplate().idtemplate)
.success(function(data, status, headers, config) {
console.log('getTimings call successful...');
console.log(data);
if(data['ok']==true) {
//create header array for the table
var currentTemplateItems = StopwatchService.getCurrentTemplateItems();
$scope.timingheaders = [];
for(var i = 0; i<currentTemplateItems.length; i++) {
var idtemplateitem = currentTemplateItems[i]['idtemplateitem'];
var templateitemname = currentTemplateItems[i]['templateitemname'];
var row = {};
row['idtemplateitem'] = idtemplateitem;
row['templateitemname'] = templateitemname;
$scope.timingheaders[i] = row;
}
console.log('header');
console.log($scope.timingheaders);
$scope.timingruns = data.timingruns;
// //set $scope.timingruns
// $scope.timingruns = [];
// //each timing row
// //loop over the data
// angular.forEach(data.timings, function(timingarray, idtimingrun) {
// var millis = timingarray['millis'];
// var idtiming = timingarray['idtiming'];
// var idtemplateitem = timingarray['idtemplateitem'];
// });
// for(var i = 0; i<data.timings.length; i++) {
// //timing row: contains a time for each of the leafs recorded
// var timing = data.timings[i];
// console.log('processing timing: ');
// console.log(timing);
// //construct a row that will be displayed in the table: the row contains a time value and is constructed in the same order as the headers
// var row = {};
//
// for (var j = 0; j < $scope.timingheaders.length; j++) {
// var colId = $scope.timingheaders[j]['id'];
// //look up the colId in the data
// //each leaf's timing
// for (var item in timing.timings) {
// var consideredtiming = timing.timings[item];
// //check if the id is what we want
// if(consideredtiming.id == colId) {
// row[j] = consideredtiming.time;
// }
// }
// }
//
// //save as row
// var resultrow = [];
// resultrow['values'] =row;
// resultrow['timingid'] = timing._id.$id;
// $scope.timingruns[i] = resultrow;
// console.log('pushed this row');
// console.log(resultrow);
// }
console.log('got the times!');
console.log($scope.timingruns);
console.log($scope.timingheaders);
refreshAggregated();
} else {
console.log('timing wasnt gotten');
}
console.log(data);
})
.error(function(data, status, headers, config) {
console.log('getTimings call failed...');
console.log(data);
});
}
$scope.sumOfTimings = function(timings) {
var sum = 0;
for(var i = 0; i<timings.length; i++) {
sum+=parseInt(timings[i].millis);
}
return sum;
}
function refreshAggregated() {
//aggregate timingruns
console.log('refreshing aggregated...');
console.log($scope.timingruns);
console.log($scope.timingheaders);
//aggregate for every timingheader
var averages = [];
var sums = [];
var amounts = [];
for(var i = 0; i<$scope.timingruns.length; i++) {
for(var k = 0; k<$scope.timingruns[i].timings.length; k++) {
var idtemplateitem = $scope.timingruns[i].timings[k].idtemplateitem;
var millis = $scope.timingruns[i].timings[k].millis;
console.log('got these millis: '+parseInt(millis));
//init
// if(sums[idtemplateitem]=='undefined') {
if(!(idtemplateitem in sums)) {
console.log('sum is empty... initing');
sums[idtemplateitem] = parseInt(0);
amounts[idtemplateitem] = parseInt(0);
console.log(sums[idtemplateitem]);
}
sums[idtemplateitem]+=parseInt(millis);
amounts[idtemplateitem]++;
console.log(sums[idtemplateitem]);
}
}
console.log('got sums');
console.log(sums);
//build averages
}
//deprecated?
$scope.startStopwatch = function() {
StopwatchService.start();
stopwatchUpdateTimer = setInterval(
function () {
fireStopwatchTimer();
}, 10);
};
//deprecated?
$scope.stopStopwatch = function() {
StopwatchService.stop();
$scope.intervalValue = StopwatchService.getValue();
clearTimeout(stopwatchUpdateTimer);
};
$scope.setActiveTemplate = function(template) {
StopwatchService.setActiveTemplate(template, getLeafs(template));
//refresh timings for the template
$scope.refreshTimings();
$scope.currentTemplateItems = StopwatchService.getCurrentTemplateItems();
};
$scope.removeTiming = function(timing) {
console.log('removing: ');
console.log(timing);
TemplateBackendService.removeTiming(timing).
success(function(data, status, headers, config) {
console.log('removeTiming call successfull...');
if(data['ok']==true) {
$scope.refreshTimings();
} else {
console.log('timing wasnt removed');
}
console.log(data);
}).
error(function(data, status, headers, config) {
console.log('removeTiming call failed...');
console.log(data);
});
};
$scope.removeTemplate = function(template) {
console.log('remove template called');
TemplateBackendService.removeTemplate(template).
success(function(data, status, headers, config) {
console.log('removeTemplate call successfull...');
if(data['ok']==true) {
refreshTemplates();
} else {
console.log('template wasnt removed');
}
console.log(data);
}).
error(function(data, status, headers, config) {
console.log('removeTemplate call failed...');
console.log(data);
});
}
function getLeafs(node) {
var result = [];
if(node['nodes'] == null || node['nodes'].length == 0) {
result.push(node);
} else {
for (var i = 0; i < node['nodes'].length; i++) {
var childleafs = getLeafs(node['nodes'][i]);
result = result.concat(childleafs);
};
}
return result;
}
function fireStopwatchTimer() {
$scope.intervalValue = StopwatchService.getValue();
$scope.$apply();
}
function refreshTemplates() {
console.log('stopwatchctrl called refreshtempltaes');
var startRefreshTemplates = new Date().getTime();
TemplateBackendService.getTemplates().
success(function(data, status, headers, config) {
console.log("got this data ("+(new Date().getTime()-startRefreshTemplates)+"ms)");
console.log(data);
console.log(data.ok);
if(data.ok) {
//save succeeded
console.log('refresh templates ok');
$scope.templates = data['templates'];
//if there is one, set the first as the active
if($scope.templates.length>0) {
$scope.setActiveTemplate($scope.templates[0]);
}
} else {
//not ok... do we explicitly call logout?
//TODO call logout
console.log('refresh templates went bad: '+data.error);
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('refresh templates ERROR');
console.log(data);
});
}
}]);
mod.controller('TimerTemplateCtrl', ['$scope', 'TemplateBackendService', function($scope, TemplateBackendService) {
//init the list
$scope.timerTemplateList = [];
$scope.newpauselength = 1000;
//some vars
var maxTreeDepth = 3;
//init the template with default name
$scope.templateitems = [];
$scope.templatename = "defaultname";
$scope.removeItem = function(item) {
$scope.templateitems.splice($scope.templateitems.indexOf(item),1);
};
$scope.addItem = function() {
$scope.templateitems.push(null);
};
$scope.toggle = function(scope) {
scope.toggle();
};
$scope.saveTemplate = function() {
console.log('saving template');
console.log($scope.templatename);
console.log($scope.templateitems);
//save a new one!
TemplateBackendService.saveTemplate($scope.templatename, $scope.templateitems).
success(function(data, status, headers, config) {
console.log("got this data");
console.log(data);
console.log(data);
if(data.ok) {
//save succeeded
console.log('save ok');
} else {
//not ok... do we explicitly call logout?
//TODO call logout
console.log('save bad');
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('save template ERROR');
console.log(data);
})
;
};
}]);
mod.controller('NavCtrl', ['$scope', 'LoginService', '$location', function ($scope, LoginService, $location) {
console.log('navctrller knows: '+LoginService.isLoggedIn());
$scope.loggedIn = function() {
return LoginService.isLoggedIn();
};
$scope.getActiveCss = function (path) {
// console.log('get activecss: '+path+' '+$location.path());
var ok = $location.path().indexOf(path) != -1;
return {
active: ok
};
};
$scope.logout = function() {
LoginService.setLoggedIn(false);
};
}]);
mod.controller('LoginCtrl', ['$scope','LoginService', '$window', 'md5', '$location', function($scope, LoginService, $window, md5, $location) {
$scope.loginErrorred = false;
$scope.loginError = "blablabla";
$scope.loggedIn = function() {
return LoginService.isLoggedIn();
}
$scope.loggedInUsername = function() {
var u = LoginService.getLoggedInUsername();
// console.log('loggedinusername requested: '+u);
return u;
}
$scope.doLogin = function () {
console.log($scope.auth);
LoginService.login($scope.auth.username, md5.createHash($scope.auth.password)).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log('login call came back OK');
console.log(data);
if(data.ok) {
//login succeeded
$scope.loginErrorred = false;
LoginService.setLoggedIn(true);
LoginService.setLoggedInUsername(data.user.username);
$location.path('/')
} else {
//didn't login, show error
$scope.loginErrorred = true;
$scope.loginError = "Couldn't login...";
//logout
$scope.logout();
}
//redirect to main
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('login ERROR');
console.log(data);
})
;
};
$scope.logout = function() {
LoginService.logout().
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log('logout call came back OK');
console.log(data);
if(data.ok) {
//login succeeded
LoginService.setLoggedIn(false);
LoginService.setLoggedInUsername(null);
} else {
//not ok... do we explicitly call logout?
//TODO call logout
}
//redirect to main
$location.path('/')
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('logout ERROR');
console.log(data);
})
;
};
}]);
mod.controller('RegisterCtrl', ['$scope', 'LoginService', 'RegisterService', 'md5', '$location', function($scope, LoginService, RegisterService, md5, $location) {
$scope.registerErrorred = false;
$scope.registerError = "blablabla";
$scope.doRegister = function () {
console.log('auth obj');
console.log($scope.auth);
//reset the error...
$scope.registerErrorred = false;
RegisterService.register($scope.auth.username, $scope.auth.email, md5.createHash($scope.auth.password))
// .then(
// function (data, status) {
// console.log('register came back');
// console.log(data);
// console.log(status);
// if (data.data.status != 200) {
// //$window.alert("Fout: "+data.data.errors[0]);
// console.log('got a loginservice error, register failed!');
// }
// else {
// console.log('register came backl with this data...');
// console.log(data.data);
// //$window.alert("GELUKT: "+data.data.user.username);
// LoginService.setLoggedIn(data.data.user != null);
// }
// }
// )
.success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log('register returned successfully');
console.log(data);
console.log(status);
if(data['ok']) {
console.log('logged in true :)');
//set us to be logged in
LoginService.setLoggedIn(true);
LoginService.setLoggedInUsername(data.newuser.username);
$location.path('/')
} else {
console.log('logged in false :(');
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('register failed');
console.log(data);
console.log(status);
if(status==400) {
$scope.registerError = data.error.message;
$scope.registerErrorred = true;
}
// $scope.registerError = status.
});
};
}]);
mod.controller('MembersCtrl', ['$scope','LoginService', '$window', function($scope, $window) {
}]);
mod.controller('MemberCtrl', ['$scope', '$routeParams', function($scope, $routeParams) {
console.log('member ctrl knows: '+$routeParams.id);
$scope.memberid = $routeParams.id;
}]);
mod.controller('NewsCtrl', ['$scope', 'NewsService', 'LoginService', function($scope, NewsService, LoginService) {
NewsService.fetchNews().then(
function (data, status) {
$scope.newsItems = data.data.news;
}
);
$scope.isLoggedIn = function() {
return LoginService.isLoggedIn();
}
$scope.submitNews = function(newNewsTitle, newNewsBody) {
NewsService.submitNews(newNewsTitle, newNewsBody).then(
function(data, status) {
console.log("submitnews has returned!");
console.log(data);
console.log(data.data.news);
console.log(data.data.errors);
//check if we are still logged in (login error might indicate we have to login again)
if(data.data.error!=null && data.data.error.nr == 2) {
console.log('we got a login error! setting the login service to loggedin = false');
LoginService.setLoggedIn(false);
return;
}
//add the result to the news items (so we don't have to reload the page)
$scope.newsItems.push(data.data.news);
//empty the input fields
$scope.newNewsBody = "";
$scope.newNewsTitle = "";
}
);
}
$scope.saveNewsItemText = function(newsItemImage) {
NewsService.saveNewsItemText(newsItemImage).then(
function(data, status) {
console.log("save newsitemtext has returned!");
console.log(data);
console.log(data.data.news);
console.log(data.data.errors);
//check if we are still logged in (login error might indicate we have to login again)
if(data.data.error!=null && data.data.error.nr == 2) {
console.log('we got a login error! setting the login service to loggedin = false');
LoginService.setLoggedIn(false);
return;
}
//add the result to the news items (so we don't have to reload the page)
$scope.newsItems.push(data.data.news);
//empty the input fields
$scope.newNewsBody = "";
$scope.newNewsTitle = "";
}
);
}
$scope.removeNewsItem = function(item) {
//look for the item to remove
var toremove = -1;
for(var i = 0; i<$scope.newsItems.length; i++) {
if($scope.newsItems[i].idnews == item.idnews) {
toremove = i;
break;
}
}
console.log('got index: '+toremove);
if(toremove>=0) {
$scope.newsItems.splice(toremove,1);
}
console.log('got to remove: ');
console.log(item);
//let the backend know to remove it as well
NewsService.removeNewsItem(item);
}
$scope.deleteNewsItemImage = function(newsItem, newsItemImage) {
//delete in the backend
NewsService.deleteNewsItemImage(newsItemImage);
//remove it in the frontend
var toremove = -1;
for(var i = 0; i<newsItem.images.length; i++) {
if(newsItem.images[i].idimage == newsItemImage.idimage) {
toremove = i;
break;
}
}
console.log('got index: '+toremove);
if(toremove>=0) {
newsItem.images.splice(toremove,1);
}
}
$scope.onFileSelect = function($files,item) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
//upload the file to the news service
NewsService.addImageToNewsItem(item, file).progress(function(evt) {
var percent = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress percent addImageToNewsItem (newsitem '+item.idnews+'): ' + percent);
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log('addimagetonewsitemservicelog: '+data);
console.log(data.newsimage);
if(data.error == null) {
//file successfully uploaded! fetch the filename and add it to the list of items
console.log('added news image item...');
console.log(data.data);
console.log(data);
item.images.push(data.newsimage);
} else {
console.log('addimagetonewsitem service errorred: '+data.error);
}
});
}
};
}]);