'use strict';
app.controller('transactionHistoryController', ['$scope', '$http', '$translate', '$location', '$timeout', '$filter', '$modal', 'blockUI', 'lib', function ($scope, $http, $translate, $location, $timeout, $filter, $modal, blockUI, lib) {

	var currentInvoiceTag = '00000000-0000-0000-0000-000000000000';
	var dateSortField = 'DateUtc';
	var defaultSortDirection = 0; // Descending

	$('.nav-tabs a').click(function (e) {
		e.preventDefault();
		e.stopPropagation();
		$(this).tab('show');
	});

	$scope.invoicesState = {
		hasPreviousInvoices: false,
		showPreviousInvoices: false,
		hasCurrentInvoices: false
	};

	$scope.parameters = {
		desiredPage: 1,
		pageSize: 10,
		sortField: dateSortField,
		sortDirection: defaultSortDirection,
		invoiceId: null
	};

	$scope.transactionTypes = [
		'PadesSignature',
		'CadesSignature',
		'XmlSignature',
		'CertAuthentication',
		'Timestamp',
		'OpenSignature',
		'AddPdfMarks'
	];

	$scope.viewDetails = viewDetails;
	$scope.previousInvoicesClick = previousInvoicesClick;
	$scope.currentInvoiceClick = currentInvoiceClick;
	$scope.nextInvoiceClick = nextInvoiceClick;
	$scope.gotoUser = gotoUser;

	var init = function () {
		handleQuery(true);

		$scope.$on('$routeUpdate', handleQuery);
	};

	// parse url query

	var parseUrl = function () {
		var params = $location.search();
		var hasParams = !angular.equals({}, params);

		parseSelectedTypesFromUrl(params);
		parseTargetUser(params);

		$scope.parameters.pageSize = params.count || 10;
		$scope.parameters.desiredPage = params.page || 1;
		$scope.parameters.success = params.success === undefined ? null : (params.success === "true");
		$scope.parameters.sortField = params.sortField || dateSortField;
		$scope.parameters.sortDirection = params.sortDirection || defaultSortDirection;
		$scope.parameters.invoiceId = params.invoiceId;

		return hasParams;
	};

	var parseSelectedTypesFromUrl = function (params) {
		var types = [].concat(params.type || []);
		$scope.parameters.selectedTypes = {};
		angular.forEach(types, function (type) {
			$scope.parameters.selectedTypes[type] = true;
		});
	};

	var parseTargetUser = function (params) {
		if ($scope.parameters.userId !== params.userId) {
			$scope.targetUser = null;
			$scope.parameters.userId = params.userId;
			if (params.userId) {
				$http.get('/Api/Users/' + params.userId).then(function (response) {
					$scope.targetUser = {
						name: response.data.username,
						id: response.data.id
					};
				}, lib.handleRestError);
			}
		}
	};

	// update url query

	var onParametersChanged = function () {
		$location.search('type', getSelectedTypesList());
		$location.search('count', $scope.parameters.pageSize);
		$location.search('page', $scope.parameters.desiredPage);
		$location.search('success', ($scope.parameters.success != null ? String($scope.parameters.success) : null));
		$location.search('sortField', $scope.parameters.sortField || dateSortField);
		$location.search('sortDirection', $scope.parameters.sortDirection || defaultSortDirection);
		$location.search('invoiceId', $scope.parameters.invoiceId || null);
	};

	var handleQuery = function (events, args) {
		var initializing = (events === true);
		var hasParams = parseUrl();
		if (hasParams) {
			fetchPage(initializing);
		}
		if (initializing) {
			$scope.$watch('parameters', function (newVal, oldVal, scope) {
				if (!angular.equals(newVal, oldVal)) {
					onParametersChanged();
				}
			}, true);
		}
	};

	// request parameters

	var getParametersModel = function () {
		return {
			type: getSelectedTypesList(),
			pageIndex: $scope.parameters.desiredPage,
			pageSize: $scope.parameters.pageSize,
			success: $scope.parameters.success,
			sortDirection: $scope.parameters.sortDirection,
			sortField: $scope.parameters.sortField,
			invoiceId: $scope.parameters.invoiceId
		};
	};

	var getSelectedTypesList = function () {
		var types = [];
		angular.forEach($scope.parameters.selectedTypes, function (value, key) {
			if (value) { types.push(key); }
		});
		return types;
	};

	// data request

	var getBaseUrl = function () {
		var url = '/Api';
		if ($scope.parameters.userId) {
			url += '/Users/' + $scope.parameters.userId;
		}
		return url;
	};

	var fetchPage = function (initializing) {
		var params = getParametersModel();

		fetchLista(params);
		fetchResumo(params);
		fetchInvoices();

		if (!initializing) {
			updateScreen();
		}
	};

	var fetchLista = function (params) {
		$scope.loading = true;

		var url = getBaseUrl() + '/Transactions';
		$http.get(url, { params: params }).then(function (response) {
			$scope.data = response.data;
			$timeout(function () {
				$scope.loading = false;
			}, 500);
		}, lib.handleRestError);
	};

	var fetchResumo = function (params) {
		var url = getBaseUrl() + '/Transactions/Synopsis';
		$scope.loading = true;

		$http.get(url, { params: params }).then(function (response) {
			$scope.resumo = response.data;
			$timeout(function () {
				$scope.loading = false;
			}, 500);
		}, lib.handdleRestError);
	};

	var fetchInvoices = function () {
		$http.get(getBaseUrl() + '/Invoices').then(function (response) {
			$scope.invoices = response.data.reverse();
			updateScreen();

			$timeout(function () {
				$scope.loading = false;
			}, 500);
		}, lib.handleRestError);
	};

	// view

	function viewDetails (transaction) {
		var modalInstance = $modal.open({
			templateUrl: views.transactionDetails,
			controller: 'transactionDetailsController',
			size: 'lg',
			resolve: {
				modelId: function () {
					return transaction.id;
				}
			}
		});
	};

	var updateScreen = function () {
		if (!$scope.invoices) {
			return;
		}

		$scope.previousInvoices = $scope.invoices.slice(1);

		$scope.invoicesState.hasPreviousInvoices = $scope.previousInvoices.length > 0;
		$scope.invoicesState.hasCurrentInvoices = $scope.invoices.length > 0;

		var currentInvoice = $scope.invoices[0];

		if (!$scope.parameters.invoiceId || !$scope.invoicesState.hasCurrentInvoices) {
			$('#nextTab').tab('show');
		} else if ($scope.parameters.invoiceId == currentInvoice.id) {
			$('#currentTab').tab('show');
		} else {
			$('#previousTab').tab('show');
		}

		if ($scope.invoicesState.hasCurrentInvoices) {
			if ($scope.parameters.invoiceId === currentInvoiceTag) {
				$scope.parameters.invoiceId = currentInvoice.id;
				onParametersChanged();
			}
		}
	};

	// click

	function previousInvoicesClick () {
		if ($scope.invoicesState.hasPreviousInvoices) {
			$scope.invoicesState.showPreviousInvoices = true;

			var beforeCurrentInvoice = $scope.previousInvoices[0];
			$scope.parameters.invoiceId = beforeCurrentInvoice.id;
			onParametersChanged();
		}
	};

	function currentInvoiceClick () {
		if ($scope.invoicesState.hasCurrentInvoices) {
			$scope.invoicesState.showPreviousInvoices = false;

			var currentInvoice = $scope.invoices[0];
			$scope.parameters.invoiceId = currentInvoice.id;
			onParametersChanged();
		}
	};

	function nextInvoiceClick () {
		$scope.invoicesState.showPreviousInvoices = false;

		$scope.parameters.invoiceId = null;
		onParametersChanged();
	};

	function gotoUser () {
		$location.search('page', null);
		$location.search('count', null);
		$location.search('username', null);
		$location.path('/user-account').search('userId', $scope.targetUser.id);
	};

	// init
	init();
}]);
