'use strict';
app.controller('transactionLimitDetailsController', ['$scope', '$http', '$modalInstance', '$timeout', '$modal', '$translate', 'blockUI', 'lib', 'transactionLimitId', 'transactionLimitName', 'transactionLimitCode', function ($scope, $http, $modalInstance, $timeout, $modal, $translate, blockUI, lib, transactionLimitId, transactionLimitName, transactionLimitCode) {

	$scope.model = null;
	$scope.isEditable = true;
	$scope.name = transactionLimitName.trim();
	$scope.code = transactionLimitCode.trim();
	$scope.id = transactionLimitId;

	var getTimeStampPlans = function () {
		$http.get('/Api/TimestampPlans').then(function (response) {
			$scope.plans = response.data;
		}, lib.handleRestError);
	};

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

	var getTransactionTypes = function () {
		var url = '/Api/Admin/TransactionTypes/';

		$scope.loading = true;
		$http.get(url).then(function (response) {
			$scope.transactionTypes = response.data;
			$timeout(function () { $scope.loading = false; }, 500);
		}, lib.handleRestError);
	};

	var init = function () {
		blockUI.start();
		getTransactionTypes();

		$http.get('/Api/Admin/TransactionLimits/' + $scope.id).then(function (response) {
			$scope.model = response.data;
			blockUI.stop();
		}, function (response) {
			lib.showRestError(response, function () {
				$modalInstance.close();
			});
		});
		getTimeStampPlans();
	};

	$scope.saveModel = function () {
		blockUI.start();
		return $http.put('/Api/Admin/TransactionLimits/' + $scope.id, {
			Id: $scope.id,
			Limit: $scope.model.limit,
			TolerancePercentage: $scope.model.tolerance,
			WarningPercentage: $scope.model.warning
		}).then(function (response) {
			$scope.model = response.data;
			$scope.id = response.data.id;
			blockUI.stop();
		}, lib.handleRestError);
	};

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


	$scope.getShowParameter = function (code) {
		for (var index in $scope.transactionTypes) {
			if (code != null && $scope.transactionTypes[index].code === code.trim()) {
				return $scope.transactionTypes[index].showParameter;
			}
		}
		return false;
	};

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

	init();
}]);
