/**
 * CustomerPrebooksCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('CustomerPrebooksCtrl', ['$scope', '$ClientsManager', 'Tasks', function ($scope, $ClientsManager, Tasks) {

	/**
	 * A list of client prebooks.
	 *
	 * @type Array
	 */
	$scope.prebooks = [];

	/**
	 * A reference to the clients manager.
	 *
	 * @type Object
	 */
	$scope.clientManager = $ClientsManager;


	/**
	 * Watches for when the client changes and
	 * reloads the prebooks.
	 *
	 * @return void
	 */
	$scope.$watch('clientManager.client', function () {
		if ($ClientsManager.isSelected()) {
			$scope.loadPrebooks($ClientsManager.getClient().id, $ClientsManager.getClientType());
		}
	}, true);


	/**
	 * Loads prebooks for a particular client.
	 *
	 * @return void
	 */
	$scope.loadPrebooks = function (client_id, client_type) {

		if ($scope.loading_prebooks) return false;

		if (client_id && client_type) {
			$scope.client_id = client_id;
			$scope.client_type = client_type;
		}

		$scope.loading_prebooks = true;

		Tasks.get({ client_id: $scope.client_id, client_type: $scope.client_type, completed: 0, prebook: 1 }, function (response) {
			$scope.prebooks = response.data;
			$scope.loading_prebooks = false;
		});
	};

}])
