/**
 * ChangeClientCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('ChangeClientCtrl', ['$scope', '$uibModalInstance', 'task', 'Client', 'Customer', 'ErrorsHandler', '$timeout', 'Tasks', function ($scope, $uibModalInstance, task, Client, Customer, ErrorsHandler, $timeout, Tasks) {

	var search_timeout;
	$scope.search = {
		type: 'client',
		query: ''
	};

	$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, sites: true, site_users: true }, function (response) {
			$scope.clients = response.data;
			$scope.loading = false;
		}, ErrorsHandler);

	};

	$scope.getSite = function () {
		if (!$scope.selected || !$scope.selected.site_id) return {};

		return _.find($scope.selected.sites, function (el) {
			return el.id == $scope.selected.site_id;
		}) || {};
	};

	$scope.select = function (item) {
		$scope.selected = item;

		// Automatically select the site and site user
		if (item.type == 'client') {
			try {
				$scope.selected.site_id = item.sites[0].id;
				$scope.selected.site_user_id = item.sites[0].users[0].id;
			}
			catch (err) {
				console.log(err);
			}
		}
	};

	$scope.submit = function () {
		Tasks.update({ id: task.id, client_id: $scope.selected.id, client_type: $scope.selected.type, site_user_id: $scope.selected.site_user_id, site_id: $scope.selected.site_id }, function (response) {
			angular.extend(task, response || {});
			$uibModalInstance.close([$scope.selected, response]);
		}, ErrorsHandler);
	};

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