'use strict';
app.controller('timestampRequestHistoryController', ['$scope', '$http', '$modalInstance', '$translate', 'blockUI', 'lib', 'modelId', function ($scope, $http, $modalInstance, $translate, blockUI, lib, modelId) {

	$scope.currentPage = 0;
	$scope.pageCount = 0;
	$scope.model = null;

	var init = function () {
		fetchPage(0);
	};

	var fetchPage = function (start) {
		blockUI.start();
		var url = '/Api/TimestampRequesters/' + modelId + '/Requests?start=' + start;
		$http.get(url).then(function (response) {
			loadItems(response.data);
			blockUI.stop();
		}, lib.handleRestError);
	};

	var loadItems = function (data) {
		$scope.itemRange = {
			begin: data.start + 1,
			end: data.start + data.count,
			total: data.totalCount
		};
		$scope.model = data;
		$scope.requests = data.requests;
		$scope.pageCount = Math.max(1, Math.ceil(data.totalCount / 10));
		$scope.currentPage = Math.floor(data.start / 10) + 1;
		//angular.forEach(data.requests, function (e, i) {
		//	if (e.digest.value.length > 48) {
		//		e.digest.compact = e.digest.value.substr(0, 24) + ' ... ' + e.digest.value.slice(-24);
		//	} else {
		//		e.digest.compact = e.digest.value;
		//	}
		//});
	};

	$scope.goTo = function (index) {
		if ($scope.currentPage !== index) {
			fetchPage((index - 1) * 10);
		}
	};

	$scope.nextPage = function () {
		if ($scope.currentPage < $scope.pageCount)
		fetchPage($scope.model.start + 10);
	};

	$scope.previousPage = function () {
		if ($scope.currentPage > 1) {
			fetchPage($scope.model.start - 10);
		}
	};

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

	$scope.pageRange = function () {
		if (!$scope.requests) return [];
		var first = Math.max(1, $scope.currentPage - 2);
		var count = Math.min(5, $scope.pageCount - first + 1);
		return Array.apply(0, Array(count)).map(function (_, i) { return i + first; });
	};

	init();
}]);
