/**
 * QuotesViewCtrl Controller
 * Extracted from invoices module
 */

Invoices.controller('QuotesViewCtrl', ['$scope', 'Quote', 'Tasks', 'ErrorsHandler', '$routeParams', '$location', 'InvoiceService', function ($scope, Quote, Tasks, ErrorsHandler, $routeParams, $location, InvoiceService) {

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

	$scope.title = 'Quotes';
	$scope.type = 'quote';
	$scope.service = InvoiceService.create(Quote);

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

	$scope.$on('$routeChangeSuccess', function (ev, currentRoute, previousRoute) {
		if ($routeParams.quoteId) {
			$scope.loadQuote($routeParams.quoteId);
		}
	});

	$scope.$watch('service.data.items', function () {
		$scope.service.calculateTotals();
	}, true);

	$scope.$watch('service.data.include_vat', function () {
		$scope.service.calculateTotals();
	});

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

	/**
	 * Loads an existing sale data
	 */
	$scope.loadQuote = function (quote_id) {

		Quote.get({ quote: quote_id, client: true }, function (response) {

			$scope.service.data = response;
			$scope.service.data.invoice_date = moment(response.invoice_date).toDate();
			$scope.service.data.include_vat = (response.include_vat == '1') ? true : false;

			$scope.service.client_search = response.client;
		});
	};

	/**
	 * Clears the form
	 */
	$scope.reset = function () {
		$location.path('quotes/new/');
	};

	/**
	 * Converts a quote to an invoice.
	 *
	 * @return null
	 */
	$scope.convertToInvoice = function () {
		Quote.convertToInvoice($scope.service.data, function (response) {
			$location.path('invoices/view/' + response.id);
		}, ErrorsHandler);
	};

}]);
