'use strict';
app.controller('certificateDetailsController', ['$scope', '$http', '$modalInstance', 'blockUI', 'lib', 'urlOrModel', 'downloadUrl', 'customButtons', function ($scope, $http, $modalInstance, blockUI, lib, urlOrModel, downloadUrl, customButtons) {

	$scope.certBreadcrumb = [];

	$scope.bottomCertificate = null;
	$scope.model = null;
	$scope.canDownload = (downloadUrl != null);
	$scope.customButtons = customButtons;

	var init = function () {
		if (typeof urlOrModel === 'string') {
			blockUI.start();
			$http.get(urlOrModel).then(function (response) {
				$scope.model = response.data;
				$scope.bottomCertificate = $scope.model;
				blockUI.stop();
			}, function (response) {
				lib.showRestError(response, function () {
					$modalInstance.close();
				});
			});
		} else {
			$scope.model = urlOrModel;
		}
	};

	$scope.hasIssuer = function () {
		return $scope.model != null && $scope.model.issuer != null;
	};

	$scope.showIssuer = function () {
		if ($scope.model.issuer) {
			$scope.model.breadcrumbIndex = $scope.certBreadcrumb.length;
			$scope.certBreadcrumb.push($scope.model);
			$scope.model = $scope.model.issuer;
		}
	};

	$scope.showIssued = function (cert) {
		while ($scope.certBreadcrumb.length !== cert.breadcrumbIndex) {
			$scope.certBreadcrumb.pop();
		}
		$scope.model = cert;
	};

	$scope.download = function () {
		blockUI.start();
		$http.get(downloadUrl).then(function (response) {
			document.location.href = response.data;
			blockUI.stop();
		}, lib.handleRestError);
	};

	$scope.clickCustomButton = function (button) {
		button.click($modalInstance, $scope.bottomCertificate);
	};

	$scope.close = function () {
		$modalInstance.close();
	};

	init();
}]);
