/**
 * EditClientCtrl Controller
 * Extracted from clients module
 */

ClientsModule.controller('EditClientCtrl', ['$scope', '$uibModalInstance', 'client', 'site', 'site_user', 'Client', 'Site', 'SiteUser', 'ErrorsHandler', '$http', function ($scope, $uibModalInstance, client, site, site_user, Client, Site, SiteUser, ErrorsHandler, $http) {

	$scope.data = angular.copy(client);
	$scope.site = site;
	$scope.site_user = site_user;

	$scope.postcode = {
		icon: 'fa fa-crosshairs'
	};

	/*
	* vytas 16.6.17
	* in the view (edit-client.blade.php) the associated select input has strings as values
	* but the tasks page loads contract_id as an integer and so there's a type mis-match
	* this $watch casts data.contact_id back to a string and so now the control is working as intended and the correct contract is pre-selected
	* if the client has a contract
	*
	* I don't think this  ever worked
	*/
	$scope.$watch('data.contract_id', function (value) {
		$scope.data.contract_id = $scope.data.contract_id.toString();
	});

	$scope.$watch('data.sla_id', function (value) {
		$scope.data.sla_id = $scope.data.sla_id.toString();
	});


	/**
	 * Saves the client and closes the modal.
	 *
	 * @return null
	 */
	$scope.save = function () {
		Client.update($scope.data, function (client_response) {
			angular.extend(client, client_response || {});

			// Save the site
			Site.update($scope.site, function (site_response) {
				angular.extend(site, site_response || {});

				// Save the site user
				SiteUser.update($scope.site_user, function (user_response) {
					angular.extend(site_user, user_response || {});
					$uibModalInstance.close();
				}, ErrorsHandler);
			}, ErrorsHandler);
		}, ErrorsHandler);
	};

	/**
	 * Closes the modal
	 *
	 * @return null
	 */
	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};

	/**
	 * Retrieves the full adress for a given postcode
	 *
	 * @return null
	 */
	$scope.lookupPostcode = function (postcode) {
		$scope.postcode.icon = 'fa fa-spinner fa-spin';

		$http.post('/clients/postcode', { postcode: postcode }).success(function (res) {

			$scope.postcode.icon = 'fa fa-crosshairs';

			angular.extend($scope.site, {
				address: res.postcode.street,
				address2: res.postcode.town
			});

		}).error(function () {
			$scope.postcode.icon = 'fa fa-crosshairs';
		});
	};

}]);
