/**
 * widgetMapCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('widgetMapCtrl', ['$scope', '$ClientsManager', 'locationHelper', '$http', '$sce', function ($scope, $ClientsManager, locationHelper, $http, $sce) {

	/**
	 * A reference to the client manager service.
	 *
	 * @type object
	 */
	$scope.client = $ClientsManager;

	/**
	 * Watches for when the client changes, and reloads the location.
	 *
	 * @return void
	 */
	$scope.$watch('client.client', function (value) {
		if (value.id)
			$scope.loadLocation();
	}, true);

	/**
	 * Watches for when the address changes and updates the map location.
	 *
	 * @return void
	 */
	$scope.$watch('address', function (value, oldValue) {
		if (value !== oldValue) {
			$scope.loadAddress();
		}
	});

	/**
	 * Watches for when the formatted address changes and strips all the spaces.
	 *
	 * @return void
	 */
	$scope.$watch('formatted_address', function (value, oldValue) {
		if (value !== oldValue) {
			$scope.formatted_address = value.replace(/\s/g, '+');
		}
	});

	/**
	 * Loads the site location and centers the map at the new coordinates adress.
	 *
	 * @return void
	 */
	$scope.loadLocation = function () {

		// If the address is set then we will use this
		if ($scope.address) {
			$scope.loadAddress();
			return false;
		}

		if ($scope.client.isClient())
			$scope.loadClientLocation();
		else
			$scope.loadCustomerLocation();
	};

	/**
	 * Loads the coordinates for a business client.
	 *
	 * @return void
	 */
	$scope.loadClientLocation = function () {
		if (!$scope.task) return false;


		var site = locationHelper.getSite($scope.client.getClient().sites, $scope.task.site_id);

		if (site) {
			$scope.formatted_address = site.address + ', ' + site.postcode;
		}
	};

	/**
	 * Loads the coordinates for a customer.
	 *
	 * @return void
	 */
	$scope.loadCustomerLocation = function () {
		// Retrive the customer data
		var client = $scope.client.getClient();

		$scope.formatted_address = client.address + ', ' + client.postcode;
	};

	/**
	 * Loads the coordinates based on a given address.
	 *
	 * @return void
	 */
	$scope.loadAddress = function () {
		return $scope.formatted_address = $scope.address;
	};

	/**
	 * Trust the given URL.
	 *
	 * @return void
	 */
	$scope.trustSrc = function (src) {
		return $sce.trustAsResourceUrl(src);
	};


}])
