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

	$scope.userId = null;
	$scope.model = null;
	$scope.dateFormats = ['Standard', 'Long', 'Short', 'LongDateShortTime', 'ShortDateLongTime'];

	$scope.settings = null;
	$scope.regionAndTime = null;

	$scope.editingCustomerId = false;
	$scope.newCustomerId = '';

	$scope.isLoggedInUserAdmin = authService.isAdmin();
	$scope.newName = '';

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

	var parseUrl = function () {
		var params = $location.search();
		$scope.userId = params.userId || null;
	};

	var getBaseUrl = function (action, userId) {
		var url = '/Api';
		var al = action.length - 1;
		url += (action[0] === '/') ? action : '/' + action;
		url += (action[al] === '/') ? '' : '/';
		return url + (userId || '');
	};

	var fetchPage = function () {
		blockUI.start();

		var urlUser = getBaseUrl($scope.userId ? '/Users' : '/User', $scope.userId);
		$http.get(urlUser).then(function (response) {
			blockUI.stop();
			$scope.model = response.data;

			var urlSettings = getBaseUrl('/Account/Settings', $scope.userId);
			$http.get(urlSettings).then(function (response) {
				loadSettings(response.data);
			}, lib.handleRestError);

			var urlRegionAndTime = getBaseUrl('/Account/RegionAndTime', $scope.userId);
			$http.get(urlRegionAndTime).then(function (response) {
				loadRegionAndTime(response.data);
			}, lib.handleRestError);

			if ($scope.isLoggedInUserAdmin) {
				var urlCustomSecurityContexts = getBaseUrl('/Users/', $scope.model.id) + '/SecurityContexts/';
				$http.get(urlCustomSecurityContexts).then(function (response) {
					loadCustomSecurityContexts(response.data);
				}, lib.handleRestError);

				var urlIntermediateCAs = getBaseUrl('/Users/', $scope.model.id) + '/IntermediateCAs/';
				$http.get(urlIntermediateCAs).then(function (response) {
					loadIntermediateCAs(response.data);
				}, lib.handleRestError);
			}

		}, lib.handleRestError);
	};

	var loadSettings = function (data) {
		$scope.settings = data;
	};

	var loadRegionAndTime = function (data) {
		$scope.regionAndTime = data;
		getDateSample();
	};

    var loadCustomSecurityContexts = function (data) {
        $scope.customSecurityContexts = data;
	};

	var loadIntermediateCAs = function (data) {
		$scope.intermediateCAs = data;
	};

	var getDateSample = function () {
		$timeout.cancel();
		$scope.loadingDateSample = true;
		$http.get('/Api/System/Date').then(function (response) {
			$scope.dateSample = response.data;
			$timeout(function () { $scope.loadingDateSample = false; }, 500);
		}, lib.handleRestError);
	};

	$scope.saveSetting = function (key, value) {
		var data = {};
		data[key] = value;
		blockUI.start();
		return $http.put(getBaseUrl('/Account/Settings', $scope.userId), data).then(function (response) {
			loadSettings(response.data);
			blockUI.stop();
		}, lib.handleRestError);
	};

	$scope.saveRegionAndTime = function (key, value) {
		var data = {};
		data[key] = value;
		blockUI.start();
		return $http.put(getBaseUrl('/Account/RegionAndTime', $scope.userId), data).then(function (response) {
			loadRegionAndTime(response.data);
			blockUI.stop();
		}, lib.handleRestError);
	};

	$scope.editTimeZone = function () {
		var promise = $q.when({ key: 'timeZoneId', value: $scope.regionAndTime.timeZone.id });
		if (!$scope.timezones) {
			blockUI.start();
			return $http.get('/Api/System/TimeZones').then(function (response) {
				blockUI.stop();
				$scope.timezones = response.data;
				return promise;
			}, lib.handleRestError);
		}
		return promise;
	};

	$scope.editCulture = function () {
		var promise = $q.when({ key: 'cultureId', value: $scope.regionAndTime.culture.id });
		if (!$scope.cultures) {
			blockUI.start();
			return $http.get('/Api/System/Cultures').then(function (response) {
				blockUI.stop();
				$scope.cultures = response.data;
				return promise;
			}, lib.handleRestError);
		}
		return promise;
	};

	$scope.editDateFormat = function () {
		return $q.when({ key: 'dateFormat', value: $scope.regionAndTime.dateFormat });
	};

	$scope.editSetting = function (key) {
		return $q.when({ key: key, value: $scope.settings[key] });
	};

	$scope.saveTransactionDetails = function (value) {
		if (value) {
			return $scope.saveSetting('storeTransactionDetails', value);
		}
		return $q(function (resolve, reject) {
			var confirmMsg = $translate.instant('usStoreTransactionDetailsConfirmation');
			var msgs = $translate.instant(['areYouSure', 'yesAgreed', 'cancel']);
			var buttons = {};
			buttons[msgs.yesAgreed] = {
				css: 'btn-danger',
				click: function (modalInstance) {
					modalInstance.close();
					$scope.saveSetting('storeTransactionDetails', value).then(resolve, reject);
				}
			};
			buttons[msgs.cancel] = {
				css: 'btn-default',
				click: function (modalInstance) {
					modalInstance.close();
					resolve();
				}
			};
			lib.showMessageBox(confirmMsg, msgs.areYouSure, buttons);
		});
	};

	$scope.resetPassword = function () {
		var userId = $scope.model.id;
		$modal.open({
			templateUrl: views.resetPasswordDialog,
			controller: 'resetPasswordDialogController',
			resolve: {
				userId: function () {
					return userId;
				}
			}
		}).result.then(init);
	};

	$scope.clearPassword = function () {
		var userId = $scope.model.id;
		$translate('udConfirmClearPassword', { username: $scope.model.username }).then(function (confirmMsg) {
			$translate(['areYouSure', 'yesClear', 'cancel']).then(function (msgs) {
				var buttons = {};
				buttons[msgs.yesClear] = {
					css: 'btn-danger',
					click: function (modalInstance) {
						modalInstance.close();
						doClearPassword(userId);
					}
				};
				buttons[msgs.cancel] = {
					css: 'btn-default',
					click: function (modalInstance) {
						modalInstance.dismiss();
					}
				};
				lib.showMessageBox(confirmMsg, msgs.areYouSure, buttons);
			});
		});
	};

	var doClearPassword = function (userId) {
		var url = $scope.userId ? getBaseUrl('Users', $scope.userId) + '/Password' : getBaseUrl('User', 'Password');
		blockUI.start();
		$http.delete(url).then(function () {
			$scope.model.hasPassword = false;
			blockUI.stop();
			$translate('udPasswordCleared').then(function (msg) {
				notifyService.success(msg);
			});
		}, lib.handleError);
	};

	$scope.grantAdmin = function () {
		$translate('udConfirmGrantAdmin', { username: $scope.model.username }).then(function (confirmMsg) {
			$translate(['areYouSure', 'udYesGrant', 'cancel']).then(function (msgs) {
				var buttons = {};
				buttons[msgs.udYesGrant] = {
					css: 'btn-warning',
					click: function (modalInstance) {
						modalInstance.close();
						setIsAdmin(true);
					}
				};
				buttons[msgs.cancel] = {
					css: 'btn-default',
					click: function (modalInstance) {
						modalInstance.close();
					}
				};
				lib.showMessageBox(confirmMsg, msgs.areYouSure, buttons);
			});
		});
	};

	$scope.revokeAdmin = function () {
		$translate('udConfirmRevokeAdmin', { username: $scope.model.username }).then(function (confirmMsg) {
			$translate(['areYouSure', 'udYesRevoke', 'cancel']).then(function (msgs) {
				var buttons = {};
				buttons[msgs.udYesRevoke] = {
					css: 'btn-danger',
					click: function (modalInstance) {
						modalInstance.close();
						setIsAdmin(false);
					}
				};
				buttons[msgs.cancel] = {
					css: 'btn-default',
					click: function (modalInstance) {
						modalInstance.close();
					}
				};
				lib.showMessageBox(confirmMsg, msgs.areYouSure, buttons);
			});
		});
	};

	var setIsAdmin = function (isAdmin) {
		blockUI.start();
		var model = $.extend(true, {}, $scope.model);
		model.isAdmin = isAdmin;
		$http.put('/Api/Users/' + $scope.model.id, model).then(function (response) {
			$scope.model = response.data;
			blockUI.stop();
		}, lib.showRestError);
	};

	$scope.blockUser = function () {
		$translate('udConfirmBlockUser', { username: $scope.model.username }).then(function (confirmMsg) {
			$translate(['areYouSure', 'udYesBlockUser', 'cancel']).then(function (msgs) {
				var buttons = {};
				buttons[msgs.udYesBlockUser] = {
					css: 'btn-danger',
					click: function (modalInstance) {
						modalInstance.close();
						setBlockUser(true);
					}
				};
				buttons[msgs.cancel] = {
					css: 'btn-default',
					click: function (modalInstance) {
						modalInstance.close();
					}
				};
				lib.showMessageBox(confirmMsg, msgs.areYouSure, buttons);
			});
		});
	};

	$scope.unblockUser = function () {
		$translate('udConfirmUnblockUser', { username: $scope.model.username }).then(function (confirmMsg) {
			$translate(['areYouSure', 'udYesUnblockUser', 'cancel']).then(function (msgs) {
				var buttons = {};
				buttons[msgs.udYesUnblockUser] = {
					css: 'btn-warning',
					click: function (modalInstance) {
						modalInstance.close();
						setBlockUser(false);
					}
				};
				buttons[msgs.cancel] = {
					css: 'btn-default',
					click: function (modalInstance) {
						modalInstance.close();
					}
				};
				lib.showMessageBox(confirmMsg, msgs.areYouSure, buttons);
			});
		});
	};

	var setBlockUser = function (isBlocked) {
		blockUI.start();
		var model = $.extend(true, {}, $scope.model);
		model.isBlocked = isBlocked;
		$http.put('/Api/Users/' + $scope.model.id, model).then(function (response) {
			$scope.model = response.data;
			blockUI.stop();
		}, lib.showRestError);
	};

	$scope.remove = function () {
		$translate('udConfirmRemove', { username: $scope.model.username }).then(function (confirmMsg) {
			$translate(['areYouSure', 'yesRemove', 'cancel']).then(function (msgs) {
				var buttons = {};
				buttons[msgs.yesRemove] = {
					css: 'btn-danger',
					click: function (modalInstance) {
						removeUser(modalInstance);
					}
				};
				buttons[msgs.cancel] = {
					css: 'btn-default',
					click: function (modalInstance) {
						modalInstance.close();
					}
				};
				lib.showMessageBox(confirmMsg, msgs.areYouSure, buttons);
			});
		});
	};

	var removeUser = function (confirmModal) {
		blockUI.start();
		var url = '/Api/Users/' + $scope.userId;
		$http.delete(url).then(function (response) {
			blockUI.stop();
			confirmModal.close();
			$scope.close();
		}, lib.handleRestError);
	};

	$scope.generateToken = function () {
		var url = getBaseUrl($scope.userId ? '/Users/' + $scope.userId : '/Account', 'LongTermToken');
		blockUI.start();
		$http.get(url).then(function (response) {
			blockUI.stop();
			$modal.open({
				templateUrl: views.tokenDialog,
				controller: 'tokenDialogController',
				resolve: {
					token: function () { return response.data.accessToken; }
				}
			});
		}, lib.handleError);
	};

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

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

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

	$scope.changePassword = function () {
		$modal.open({
			templateUrl: views.changePasswordDialog,
			controller: 'changePasswordController'
		});
	};

	$scope.editCustomerId = function () {
		$scope.newCustomerId = $scope.model.customerId;
		$scope.editingCustomerId = true;
	};

	$scope.confirmCustomerId = function () {
		blockUI.start();
		var model = $.extend(true, {}, $scope.model);
		model.customerId = $scope.newCustomerId;
		$http.put('/Api/Users/' + $scope.model.id, model).then(function (response) {
			$scope.model = response.data;
			$scope.editingCustomerId = false;
			blockUI.stop();
		}, lib.showRestError);
	};

	$scope.cancelCustomerId = function () {
		$scope.editingCustomerId = false;
    };

    $scope.showContext = function (context) {
        var modalInstance = $modal.open({
            templateUrl: views.securityContextDetails,
            controller: 'securityContextDetailsController',
            size: 'lg',
            resolve: {
                securityContextId: function () {
                    return context.id;
                },
                canEditSystem: null
            }
        });
        modalInstance.result.then(init, init);
	};

	$scope.createSecurityContext = function () {
		if ($scope.newName === '') {
			$translate(['message', 'scFillContextName']).then(function (msgs) {
				lib.showAlert(msgs.message, msgs.scFillContextName);
			});
			return;
		}
		blockUI.start();
		$http.post('/Api/SecurityContexts', {
			name: $scope.newName,
			userId: $scope.userId
		}).then(function (response) {
			$scope.customSecurityContexts.push(response.data);
			$scope.newName = '';
			blockUI.stop();
		}, lib.handleRestError);
	};

	$scope.showCA = function (ca) {
		$translate(['remove']).then(function (msgs) {
			var url = '/Api/IntermediateCAs/' + ca.thumbprint;
			var buttons = {};
			buttons[msgs.remove] = {
				css: 'btn-danger',
				click: removeCA
			};
			lib.showCertificate(url, url + '/DownloadLink', buttons);
		});
	};

	var removeCA = function (certDetailsModalInstance, certModel) {
		$translate('scConfirmCARemoval', { name: certModel.subjectDisplayName }).then(function (confirmMsg) {
			$translate(['areYouSure', 'yesRemove', 'cancel']).then(function (msgs) {
				var buttons = {};
				buttons[msgs.yesRemove] = {
					css: 'btn-danger',
					click: function (confirmModalInstance) {
						blockUI.start();
						$http.delete('/Api/IntermediateCAs/' + certModel.thumbprint).then(function (response) {
							blockUI.stop();
							confirmModalInstance.close();
							certDetailsModalInstance.close();
							init();
						}, lib.handleRestError);
					}
				};
				buttons[msgs.cancel] = {
					css: 'btn-default',
					click: function (confirmModalInstance) {
						confirmModalInstance.close();
					}
				};
				lib.showMessageBox(confirmMsg, msgs.areYouSure, buttons);
			});
		});
	};

	$scope.upload = function () {
		$timeout(uploadCA, 200);
	};

	var clear = function () {
		angular.element("input[type='file']").val(null);
	};

	var filesToUpload = 0;
	var handleUploadError = function (arg) {
		handleFileUploadComplete();
		lib.handleRestError(arg);
	};

	var handleFileUploadComplete = function () {
		filesToUpload--;
		if (filesToUpload == 0) {
			clear();
			blockUI.stop();
		}
	}

	var uploadCA = function () {
		if ($scope.caFiles != null) {
			blockUI.start();
			var url = '/Api/' + $scope.userId + '/IntermediateCAs';

			filesToUpload = $scope.caFiles.length;
			angular.forEach($scope.caFiles, function (file) {
				fileUpload.uploadFileToUrl(file, url).then(function (response) {
					$scope.intermediateCAs.push(response.data);
					handleFileUploadComplete();
				}, handleUploadError);
			});
		}
	};

	$scope.close = function () {
		window.history.back();
	};

	init();
}]);
