/**
 * PagesRepairsCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('PagesRepairsCtrl', ['$scope', '$ClientsManager', 'Repair', 'ErrorsHandler', '$location', 'Messenger', 'PartsService', 'Page', '$uibModal', '$rootScope', 'InvoiceBookingService', 'SalesBookingService', function ($scope, $ClientsManager, Repair, ErrorsHandler, $location, Messenger, PartsService, Page, $uibModal, $rootScope, InvoiceBookingService, SalesBookingService) {

	/**
	 * The repair data
	 *
	 * @object
	 */
	$scope.data = {};

	/**
	 * Bind the invoice service to the scope
	 *
	 * @object
	 */
	$scope.InvoiceService = InvoiceBookingService;

	/**
	 * Bind the sales service to the scope
	 *
	 * @object
	 */
	$scope.SalesService = SalesBookingService;

	/**
	 * All the possible repair statuses.
	 *
	 * @type array
	 */
	$scope.statuses = [];

	/**
	 * A local reference to the clients manager service.
	 *
	 * @object
	 */
	$scope.clientManager = $ClientsManager;

	/**
	 * The total price.
	 *
	 * @type Float
	 */
	$scope.total = 0;

	/**
	 * A reference to the PartsService object that hold
	 * all shared data related to parts.
	 *
	 * @type Object
	 */
	$scope.PartsService = PartsService;


	// --------------------------
	// Functions below
	// --------------------------

	/**
	 * Watch the labour and update the total price
	 * when this changes.
	 *
	 * @return void
	 */
	$scope.$watch('data.labour', function () {
		$scope.total = (parseFloat($scope.data.labour) + parseFloat(PartsService.getTotal())).toFixed(2);
	});

	$scope.$watch('PartsService.total', function () {
		$scope.total = (parseFloat($scope.data.labour) + parseFloat(PartsService.getTotal())).toFixed(2);
	});

	$scope.$watch('return', function (value) {
		// Remove the return id if the user selects 'not a return'
		if (value == '0') {
			$scope.data.return_id = null;
		}
	});

	/**
	 * Watch when the taskId becomes active and load the page.
	 *
	 * @return null
	 */
	$scope.$watch('taskId', function (value) {
		if (value) {
			Page.setTitle($scope.taskId);
			$scope.loadData();
		}
	});

	/**
	 * Loads the repair data, by sending an ajax request.
	 *
	 * @returns void
	 */
	$scope.loadData = function () {
		Repair.get({ taskId: $scope.taskId }, function (res) {
			$scope.data = res.data;
			$scope.return = (res.data.return_id) ? 1 : 0;
			PartsService.setParts(res.data.parts);
			$ClientsManager.setClient(res.data.client);
			$ClientsManager.setClientType(res.data.client_type);
			$ClientsManager.unify(res.data.site, res.data.site_user);
			$rootScope.$broadcast('task-updated', res.data);

		}, ErrorsHandler);
	};

	/**
	 * Updates the repair data
	 */
	$scope.update = function (ev) {
		Repair.update($scope.data, function (res) {
			angular.extend($scope.data, res || {});
			$scope.return = (res.return_id) ? 1 : 0;
			$scope.labour_changed = false;
			$scope.booking_fee_changed = false;
			$scope.invoice_number_changed = false;
			Messenger("I've succesfully saved the repair!");
			$rootScope.$broadcast('task-updated', res);
		}, ErrorsHandler);
	};

	/**
	 * Change the user who the repair is assigned to.
	 *
	 * @param  integer id - the id of the new user.
	 * @return void
	 */
	$scope.assignTo = function (id) {
		Repair.update({ id: $scope.data.id, assigned_to: id }, function (res) {
			$scope.data.assigned_to = id;
			$scope.data.user = res.user;
			$rootScope.$broadcast('task-updated', res);
		}, ErrorsHandler);
	};

	/**
	 * Retrieves the current selected status object.
	 *
	 * @return object
	 */
	$scope.getStatus = function () {
		return _.find($scope.statuses, function (el) { return el.id == $scope.data.status_id; });
	};

	/**
	 * Returns the status name.
	 *
	 * @return string
	 */
	$scope.getStatusName = function () {
		var status = $scope.getStatus();

		return (status) ? status.name : '';
	};

	/**
	 * Updates the current task status.
	 *
	 * @param  integer id - status id
	 * @return void
	 */
	$scope.updateStatus = function (id) {
		// Find the status being changed to
		var status = _.find($scope.statuses, function (el) { return el.id == id; });

		if (status && status.completed == '1' && $scope.data.labour == '0' && !$scope.data.no_price_reason) {
			var modalInstance = $uibModal.open({
				templateUrl: 'modals/no-price-confirmation.html',
				controller: 'TaskNoPriceCtrl',
			});

			modalInstance.result.then(function (reason) {
				Repair.update({ id: $scope.data.id, status_id: id, no_price_reason: reason }, function (res) {
					$scope.data.status_id = id;
					$scope.data.no_price_reason = reason;
					$rootScope.$broadcast('task-updated', res);
				}, ErrorsHandler);
			});
		}
		else {
			Repair.update({ id: $scope.data.id, status_id: id }, function (res) {
				$scope.data.status_id = id;
				$rootScope.$broadcast('task-updated', res);
			}, ErrorsHandler);
		}
	};

	/**
	 * Retrieve the name of the person who needs to deliver the repair.
	 *
	 * @return String
	 */
	$scope.getDeliveryUserName = function () {
		if (!$scope.data.delivered_by)
			return 'No one';

		var user = _.find($scope.users, function (el) { return el.id == $scope.data.delivered_by; });

		return (user) ? user.first_name + '' + user.last_name : '';
	};

	/**
	 * Updates the person who has to deliver the repair back.
	 *
	 * @param  integer id - the id of the new user.
	 * @return void
	 */
	$scope.deliverBy = function (id) {
		Repair.update({ id: $scope.data.id, delivered_by: id }, function (res) {
			$scope.data.delivered_by = id;
			$rootScope.$broadcast('task-updated', res);
		}, ErrorsHandler);
	};

	/**
	 * Mark repair as being paid.
	 *
	 * @return void
	 */
	$scope.paid = function () {
		Repair.update({ id: $scope.data.id, paid: 1 }, function (response) {
			$scope.data = response;
			$rootScope.$broadcast('task-updated', res);
		}, ErrorsHandler);
	};

}]);
