app.controller('repo.deploy', ['$scope', '$stateParams', '$interval', 'deployments', 'repos', function($scope, $stateParams, $interval, deployments, repos) {
	$scope.owner = $stateParams.owner
	$scope.repo = $stateParams.repo
	$scope.deployments = deployments
	$scope.deployment = null
	$scope.watcher = null
	$scope.log = ""

	$scope.activate = function() {
		$scope.deployments.set_repo($stateParams.owner, $stateParams.repo)
			.then(function() {
				$scope.deployments.get($stateParams.id)
					.then(function(deploy) {
						$scope.deployment = deploy
						$scope.watch_log()
					})		
			})
	}
	$scope.activate()

	$scope.watch_log = function() {
		$scope.deployments.get_log_output($scope.deployment.id)
			.then(function(log) {
				$scope.log = log
			})
		$scope.watcher = $interval(function() {
			$scope.deployments.get_log_output($scope.deployment.id)
				.then(function(log) {
					$scope.log = log
				})
		}, 2500)
	}

	$scope.deploy_status_for = function(deploy_id) {
			classes = ["glyphicon"]
			state = "unknown"

			if ($scope.deployments.statuses[deploy_id]) {
				state = $scope.deployments.statuses[deploy_id].state		
			}

			classes.push(state)

			switch (state) {
				case "success":
					classes.push("glyphicon-ok")
					break
				case "pending":
					classes.push("glyphicon-time")
					break
				case "failure":
				case "error":
					classes.push("glyphicon-remove")
					break
				case "unknown":
					classes.push("glyphicon-question-sign")
					break	
			}

			return classes
		}
}])