'use strict';

// Claims controller
angular.module('claims').controller('ClaimsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Claims',
	function($scope, $stateParams, $location, Authentication, Claims ) {
		$scope.authentication = Authentication;

		// Create new Claim
		$scope.create = function() {
			// Create new Claim object
			var claim = new Claims ({
				claim_number: this.claim_number,
                claim_adjuster: this.claim_adjuster,
                peril: this.peril
			});

			// Redirect after save
			claim.$save(function(response) {
				$location.path('claims/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Claim
		$scope.remove = function( claim ) {
			if ( claim ) { claim.$remove();

				for (var i in $scope.claims ) {
					if ($scope.claims [i] === claim ) {
						$scope.claims.splice(i, 1);
					}
				}
			} else {
				$scope.claim.$remove(function() {
					$location.path('claims');
				});
			}
		};

		// Update existing Claim
		$scope.update = function() {
			var claim = $scope.claim ;

			claim.$update(function() {
				$location.path('claims/' + claim._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Claims
		$scope.find = function() {
			$scope.claims = Claims.query();
		};

		// Find existing Claim
		$scope.findOne = function() {
			$scope.claim = Claims.get({ 
				claimId: $stateParams.claimId
			});
		};
	}
]);