app.controller('repo.candidates', ['$scope', '$stateParams', '$modal', 'deployments', 'candidates', function($scope, $stateParams, $modal, deployments, candidates) {
	$scope.owner = $stateParams.owner
	$scope.repo = $stateParams.repo
	$scope.deployments = deployments
	$scope.candidates = candidates

	$scope.activate = function() {
		candidates.set_repo($stateParams.owner, $stateParams.repo)
		deployments.set_repo($stateParams.owner, $stateParams.repo)
	}
	$scope.activate()

	$scope.deploy = function(branch, ref, environment) {
		var modalInstance = $modal.open({
			templateUrl: 'deploy_modal.html',
			controller: 'deploy_modal',
			resolve: {
				branch: function() {
					return branch
				},
				environment: function() {
					return environment
				}
			}
		})

		modalInstance.result.then(function(settings) {
			return deployments.create(branch, ref, environment, settings.description)
		})
	}

	$scope.state_classes = function(state) {
		classes = ["glyphicon", 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
	}

	$scope.deployable_classes = function(state) {
		if (state != "success") {
			return ["disabled"]
		}

		return []
	}

	$scope.write_default_config = function() {
		config.write_default_config($scope.owner, $scope.repo)
			.then(function() {
				repos.load_settings($routeParams.owner, $routeParams.repo)
					.then(function() {
						candidates.set_repo($routeParams.owner, $routeParams.repo)
						branches.set_repo($routeParams.owner, $routeParams.repo)
						deployments.set_repo($routeParams.owner, $routeParams.repo)		
					})
			})
	}

	$scope.previous_panel = ""
	$scope.previous_candidates = {}
	$scope.previous_loading = {}
	$scope.toggle_previous_candidates = function(branch) {
		if ($scope.previous_panel == branch) {
			$scope.previous_panel = ""
			$scope.previous_candidates[branch] = []
		} else {
			$scope.previous_panel = branch

			$scope.previous_loading[branch] = true
			candidates.load_previous(branch)
				.then(function(candidates) {
					$scope.previous_candidates[branch] = candidates
					$scope.previous_loading[branch] = false
				})
		}
	}
}])

app.controller('deploy_modal', ['$scope', '$modalInstance', 'branch', 'environment', function($scope, $modalInstance, branch, environment) {
	$scope.branch = branch
	$scope.environment = environment
	$scope.settings = {}

	$scope.ok = function() {
		$modalInstance.close($scope.settings)
	}

	$scope.cancel = function() {
		$modalInstance.dismiss()
	}
}])