/**
 * DuplicatesCtrl Controller
 * Extracted from clients module
 */

ClientsModule.controller('DuplicatesCtrl', ['$scope', '$uibModalInstance', 'Customer', 'Client', 'ErrorsHandler', '$timeout', 'currentClient', '$http', 'apiUrl', function ($scope, $uibModalInstance, Customer, Client, ErrorsHandler, $timeout, currentClient, $http, apiUrl) {
	var search_timeout;
	$scope.search = {
		type: 'client',
		query: currentClient.name
	};
	$scope.data = [];

	$scope.$watch('search.query', function (value) {
		if (search_timeout) $timeout.cancel(search_timeout);

		search_timeout = $timeout(function () {
			$scope.load();
		}, 300);
	});

	$scope.$watch('search.type', function () {
		$scope.load();
	});

	$scope.load = function () {
		$scope.loading = true;

		var model = ($scope.search.type == 'customer') ? Customer : Client;

		model.get({ name: $scope.search.query }, function (response) {
			$scope.clients = _.reject(response.data, function (el) { return el.id == currentClient.id });
			$scope.loading = false;
		}, ErrorsHandler);

	};

	$scope.select = function (item) {
		if ($scope.exists(item)) return false;
		$scope.data.push(item);
	};

	$scope.remove = function (item) {
		$scope.data = _.reject($scope.data, function (el) {
			return el.id == item.id;
		});
	};

	$scope.exists = function (item) {
		var client = _.find($scope.data, function (el) {
			return el.id == item.id;
		});

		return (client) ? true : false;
	};

	$scope.merge = function () {
		$http.post(apiUrl('clients/helpers/merge-accounts'), { data: $scope.data, client: currentClient })
			.success(function (response) {
				$uibModalInstance.close(response);
			})
			.error(ErrorsHandler);
	};

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

}]);
