/**
 * AddClientCtrl Controller
 * Extracted from clients module
 */

ClientsModule.controller('AddClientCtrl', ['$scope', '$uibModalInstance', '$uibModal', '$location', 'Client', 'ErrorsHandler', function ($scope, $uibModalInstance, $uibModal, $location, Client, ErrorsHandler) {

	/**
	 * The current wizard step
	 *
	 * @type Integer
	 */
	$scope.step = 1;

	/**
	 * The last step of the wizard
	 *
	 * @type Integer
	 */
	$scope.last_step = 3;

	/**
	 * The entire client data object.
	 *
	 * @type Object
	 */
	$scope.data = {
		sites: []
	};

	// -----------------------------------------
	// Functions below
	//

	$scope.SiteModal = function () {
		var modalInstance = $uibModal.open({
			templateUrl: 'clients/site.html',
			controller: 'SiteModalCtrl',
			backdrop: 'static',
			windowClass: 'modal-nested',
			resolve: {
				DoNotSave: function () {
					return true;
				},
				client_id: function () {
					return null;
				},
				data: function () {
					return null;
				}
			}
		});

		modalInstance.result.then(function (site) {
			$scope.data.sites.push(site);
		});
	};

	$scope.removeSite = function (site) {
		$scope.data.sites = _.reject($scope.data.sites, function (el) { return el === site; });
	};

	$scope.SiteUserModal = function (site) {
		var modalInstance = $uibModal.open({
			templateUrl: 'clients/site-user.html',
			controller: 'SiteUserModalCtrl',
			backdrop: 'static',
			windowClass: 'modal-nested',
			resolve: {
				DoNotSave: function () {
					return true;
				},
				site: function () {
					return site;
				},
				data: function () {
					return null;
				}
			}
		});

		modalInstance.result.then(function (user) {
			if (!site.users) site.users = [];
			site.users.push(user);
		});
	};

	$scope.removeSiteUser = function (site, user) {
		site.users = _.reject(site.users, function (el) { return el === user; });
	};

	$scope.next = function () {
		if ($scope.step < $scope.last_step) {
			var formName = 'step_' + $scope.step + '_form';

			if ($scope[formName].$valid) {
				$scope.step++;
			} else {
				$scope[formName].$submitted = true;
			}
		}
	};

	$scope.back = function () {
		if ($scope.step > 1) $scope.step--;
	};

	$scope.submit = function () {
		$scope.saving = true;

		Client.save($scope.data, function (response) {
			$location.path('/client/' + response.id);
			$uibModalInstance.close(response);
		}, function (error) {
			$scope.saving = false;
			ErrorsHandler(error);
		});
	};

	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};

}]);
