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

	$scope.authorized = false;
	$scope.parameters = { pageIndex: 1, pageSize: 10, isBlocked: null };
	$scope.data = null;
	$scope.search = function () {
		onParametersChanged();
	};

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

		$scope.authorized = true;

		parseUrl();
		handleQuery(true);

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

	// update url query

	var parseUrl = function () {
		var params = $location.search();
		var hasParams = !angular.equals({}, params);
		if (hasParams) {
			$scope.parameters.pageSize = params.count || 10;
			$scope.parameters.pageIndex = params.page || 1;
			$scope.username = params.username;
			$scope.isBlocked = params.isBlocked === undefined ? null : (params.isBlocked === "true");
		}
		return hasParams;
	};

	var onParametersChanged = function () {
		$location.search('count', $scope.parameters.pageSize);
		$location.search('page', $scope.parameters.pageIndex);
		$location.search('username', $scope.username);
		$location.search('isBlocked', ($scope.parameters.isBlocked != null ? String($scope.parameters.isBlocked) : null));
	};

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

	// data request
	var getRequestModel = function () {
		return {
			pageSize: $scope.parameters.pageSize,
			pageIndex: $scope.parameters.pageIndex,
			isBlocked: $scope.parameters.isBlocked,
			username: $scope.username
		};
	};

	var fetchPage = function () {
		var url = '/Api/Users';
		$scope.loading = true;
		$http.get(url, { params: getRequestModel() }).then(function (response) {
			$scope.data = response.data;
			$timeout(function () { $scope.loading = false; }, 500);
		}, lib.handleRestError);
	};

	// create and view users

	$scope.create = function () {
		$modal.open({
			templateUrl: views.userCreate,
			controller: 'userCreateController',
			size: 'lg'
		}).result.then(init, init);
	};

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

	// view history and transactions

	$scope.showEvents = function (user) {
		$location.path('/events').search('userId', user.id);
	};

	$scope.showTransactions = function (user) {
		$location.path('/transactions').search('userId', user.id);
	};

	$scope.showTransactionLimits = function (user) {
		$location.path('/transaction-limits').search('userId', user.id);
	};

	init();
}]);
