/**
 * QuotesBrowseCtrl Controller
 * Extracted from invoices module
 */

Invoices.controller('QuotesBrowseCtrl', ['$scope', 'Quote', 'ErrorsHandler', '$filter', '$location', '$paginator', '$timeout', 'InvoiceService', function ($scope, Quote, ErrorsHandler, $filter, $location, $paginator, $timeout, InvoiceService) {

	// ------------------------------------------------------------------------
	//
	//	SCOPE VARIABLES BELOW -->
	//
	// ------------------------------------------------------------------------

	// The list of sales currently loaded
	$scope.data = [];
	$scope.title = 'Browse quotes';
	$paginator = angular.copy($paginator);
	$scope.paginator = $paginator;
	$scope.filters = {};
	$scope.service = InvoiceService.create(Quote);
	var search_timeout;

	// ------------------------------------------------------------------------
	//
	//	WATCHERS AND EVENT LISTENERS BELOW -->
	//
	// ------------------------------------------------------------------------

	$paginator.setOnPageChange(function (page) {
		$scope.loadData(page);
	});

	$scope.$watch('filters', function (value) {

		if (search_timeout) $timeout.cancel(search_timeout);

		search_timeout = $timeout(function () {
			$scope.loadData();
		}, 100);
	}, true);

	// ------------------------------------------------------------------------
	//
	//	FUNCTIONS BELOW THIS LINE -->
	//
	// ------------------------------------------------------------------------

	$scope.loadInvoice = function (sale) {
		$location.path('/quotes/view/' + sale.id + '/');
	};

	$scope.loadData = function (page) {
		if (!page) page = 1;

		var prepared_filter = angular.copy($scope.filters);
		angular.extend(prepared_filter, { page: page, type: 'quote', client: true });

		if ($scope.filters.client) {
			prepared_filter.client_id = $scope.filters.client.id;
			prepared_filter.client_type = $scope.filters.client.type;
		}

		Quote.get(prepared_filter, function (response) {
			$scope.data = response.data;
			$paginator.setFromResponse(response);
		}, ErrorsHandler);
	};

}]);
