'use strict';
app.controller('invoiceDetailsController', ['$scope', '$http', '$translate', '$location', '$timeout', '$filter', 'blockUI', 'lib', 'modelId', '$modalInstance', 'userId', 'authService',  function ($scope, $http, $translate, $location, $timeout, $filter, blockUI, lib, modelId, $modalInstance, userId, authService) {

	$scope.getQuery = function () {
		var query = "";

		if (authService.isAdmin() && userId)
			query += "userId=" + userId + "&";

		if ($scope.data)
			query += "invoiceId=" + $scope.data.id + "&";

		return query;
	};

	$scope.parameters = { id: modelId };
	$scope.userId = userId;

	var init = function () {
		if (!lib.checkIsAuthenticated()) {
			return;
		}

		$scope.fetch()
	};

	$scope.fetch = function () {
		var url = '/Api/Invoices/' + $scope.parameters.id;

		blockUI.start();

		$http.get(url).then(function (response) {
			$scope.data = response.data;
			$timeout(function () {
				blockUI.stop();
			}, 500);
		}, lib.handleRestError);
	};

	$scope.totalSuccess = function () {
		if ($scope.data != null) {
			return $scope.data.transactions.reduce(function (item1, item2) {
				return item1 += item2.count.success;
			}, 0);
		} else {
			return 0;
		}
	}

	$scope.totalFail = function () {
		if ($scope.data != null) {
			return $scope.data.transactions.reduce(function (item1, item2) {
				return item1 += item2.count.fail;
			}, 0);
		} else {
			return 0;
		}
	}

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

	init();

}]);
