/**
 * PagesMessageCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('PagesMessageCtrl', ['$scope', '$ClientsManager', 'Message', 'ErrorsHandler', '$location', 'Messenger', 'Page', function ($scope, $ClientsManager, Message, ErrorsHandler, $location, Messenger, Page) {

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

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

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


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

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

	/**
	 * Loads the repair data, by sending an ajax request.
	 *
	 * @returns void
	 */
	$scope.loadData = function () {
		Message.get({ messageId: $scope.messageId }, function (res) {
			$scope.data = res;
			$ClientsManager.setClient(res.client);
			$ClientsManager.setClientType(res.client_type);

		}, ErrorsHandler);
	};

	/**
	 * Updates the repair data
	 */
	$scope.update = function (ev) {
		Message.update($scope.data, function (res) {
			$scope.data = res;
			$scope.labour_changed = false;
			Messenger("I've succesfully saved the message!");
		}, 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) {
		Message.update({ id: $scope.data.id, assigned_to: id }, function (res) {
			$scope.data.assigned_to = id;
			$scope.data.user = res.user;
		}, ErrorsHandler);
	};

	/**
	 * Close or open a message
	 *
	 * @return void
	 */
	$scope.closed = function (status) {
		Message.update({ id: $scope.data.id, closed: status }, function (res) {
			$scope.data = res;
			Messenger("I've succesfully saved the message!");
		}, ErrorsHandler);
	};

}]);
