app.service('candidates', ['$q', '$http', '$cookies', '$interval', 'config', function($q, $http, $cookies, $interval, config) {
	var that = this

	this.set_repo = function(owner, repo) {
		var deferred = $q.defer()

		if (that.current_interval != null) {
			$interval.cancel(that.current_interval)
		}

		that.owner = owner
		that.repo = repo
		that.current = []
		that.current_interval = null

		that.load_current()
			.then(function() {
				that.current_interval = $interval(that.load_current, 30000)
				deferred.resolve()
			})

		return deferred.promise
	}

	this.load_current = function() {
		var deferred = $q.defer()

		c = {
			params: {
				owner: that.owner,
				name: that.repo,
			}
		}
		$http.get(config.skadi_host+"/v1/candidate/current", c)
			.success(function(candidates) {
				that.current = candidates
				deferred.resolve()
			})

		return deferred.promise
	}
	
	this.load_previous = function(branch) {
		var deferred = $q.defer()

		c = {
			params: {
				owner: that.owner,
				name: that.repo,
				branch: branch,
			}
		}
		$http.get(config.skadi_host+"/v1/candidate/previous", c)
			.success(function(candidates) {
				deferred.resolve(candidates)
			})

		return deferred.promise
	}
}]);