app.service('repos', ['$q', '$http', '$cookies', 'config', function($q, $http, $cookies, config) {
	this.loaded = false
        this.settings_exist = true
	this.by_org = {}
	this.settings = null

	var that = this

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

		if (that.loaded) {
			deferred.resolve(that.by_org)
			return deferred.promise
		}

		that.by_org = {}
		
		c = {
			params: {
				per_page: 100
			}
		}

		$http.get(config.skadi_host+"/v1/user/repos", c)
			.success(function(data) {
				for (var i = 0; i < data.length; i++) {
					if (that.by_org[data[i].owner.login] == null) {
						that.by_org[data[i].owner.login] = []
					}
					that.by_org[data[i].owner.login].push(data[i])
				};

				// sort repos by updated_at for each org
				for (var org in that.by_org) {
					that.by_org[org].sort(function(a, b) {
						date_a = new Date(a.updated_at)
						date_b = new Date(b.updated_at)

						if (date_a < date_b) {
							return 1
						} else if (date_b < date_a) {
							return -1
						} else {
							return 0
						}
					})
				}

				that.loaded = true
				deferred.resolve(that.by_org)
			})
			.error(function(data) {
				deferred.reject(data)
			})

		return deferred.promise
	}

	this.load_settings = function(owner, name) {
		var deferred = $q.defer()

		$http.get(config.skadi_host+"/v1/repos/"+owner+"/"+name+"/settings")
			.success(function(settings) {
				if(settings.deploy.graphite_targets) {
				    var width = 640 / settings.deploy.graphite_targets.length;
				    settings.deploy.graphite_width = width;
				    var items = [];
				    for(var i=0; i<settings.deploy.graphite_targets.length; i++) {
					var url_params = "?width=" + width + "&height=100&bgcolor=white&fgcolor=darkgray&hideLegend=true&yMin=0&from=-2hours"
					    + "&target=" + settings.deploy.graphite_targets[i];
					var item = {url: "http://graphite.internal.justin.tv/render" + url_params,
						    link_url: "http://graphite.internal.justin.tv/" + url_params,
						    target: settings.deploy.graphite_targets[i]};
					items.push(item);
				    }
				    settings.deploy.graphite_items = items;
				}
				that.settings = settings
				deferred.resolve(settings)
			})
                        .error(function(data) {
                                that.settings_exist = false
                        })

		return deferred.promise
	}
}]);

setInterval(function(){
    $('.graphite_chart').each(function(index) {$(this).attr('src', $(this).data('original-src')+"&cache-breaker=" + Math.random());});
}, 5000);
