/**
 * BookingsMainCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('BookingsMainCtrl', ['$scope', 'Client', '$routeParams', '$location', 'Customer', 'ErrorsHandler', 'CustomerForm', 'ClientForm', '$rootScope', '$ClientsManager', '$uibModal', '$timeout', function ($scope, Client, $routeParams, $location, Customer, ErrorsHandler, CustomerForm, ClientForm, $rootScope, $ClientsManager, $uibModal, $timeout) {

	// ------------------------------------------------------------------------
	//
	//	PRIVATE FUNCTIONS (HELPERS) BELOW THIS LINE -->
	//
	// ------------------------------------------------------------------------
	var filterClientsDatum = function (res) {
		if (res.success) {
			var datums = [];
			_.each(res.data, function (item) {
				datums.push({
					value: item.name,
					data: item,
					type: 'client',
					tokens: item.name.split(' ')
				});
			});

			return datums;
		} else {
			return [];
		}
	};

	var filterCustomersDatum = function (res) {
		if (res.success) {
			var datums = [];
			_.each(res.data, function (item) {
				datums.push({
					value: item.name,
					data: item,
					type: 'customer',
					tokens: [item.first_name, item.last_name]
				});
			});

			return datums;
		} else {
			return [];
		}
	};

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

	// The search options passed to typeahead
	$scope.searchCustomers = [
		{
			name: 'clients',
			header: '<h6 class="typeahead-header">Clients</h6>',
			remote: {
				url: Client.getSearchUrl() + '%QUERY',
				filter: filterClientsDatum
			}
		},
		{
			name: 'customers',
			header: '<h6 class="typeahead-header">Customers</h6>',
			remote: {
				url: Customer.getSearchUrl() + '%QUERY',
				filter: filterCustomersDatum
			}
		}
	];

	// Customer popup options
	$scope.customerModalOpts = {
		onClose: function () {
			// we would like to clear the form every time the modal closes
			// customerForm.clear();
		}
	};

	$scope.clientManager = $ClientsManager;

	CustomerForm.onCreate = function (data) {
		// Close the modal
		$scope.customerModal.dismiss();

		// Mark this as the selected customer
		$ClientsManager.setClient(data);
		$ClientsManager.setClientType("customer");

		// Update the field in the search box
		$scope.client_search = data.name;

	};

	ClientForm.onCreate = function (data) {

		// Close the modal
		$scope.showClientForm = false;

		// Mark this as the selected customer
		$ClientsManager.setClient(data);
		$ClientsManager.setClientType("client");

		// Update the field in the search box
		$scope.client_search = data.name;

	};

	CustomerForm.onUpdate = function (data) {
		// Close the modal
		$scope.customerModal.dismiss();

		// Clear the fake route parameter
		$routeParams.customerId = null;

		// Update the data
		$ClientsManager.setClient(data);
		$ClientsManager.setClientType("customer");

	};



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

	// If no location is specified, load the repairs
	if (!$location.path()) {
		// $location.path('bookings/repair');
	}

	$scope.$on('$routeChangeSuccess', function () {
		// nadeem added $routeParams.projectId checking on 12.2.17 to enable project and client task tie-ins
		if ($routeParams.projectId && typeof ($routeParams.projectId) != 'undefined') {
			$scope.projectId = $routeParams.projectId;
		}
		if ($routeParams.clientId && $routeParams.clientType) {
			if ($routeParams.clientType == 'customer') {
				Customer.get({ customer: $routeParams.clientId }, function (response) {
					$ClientsManager.setClient(response.data);
					$ClientsManager.setClientType('customer');
				}, ErrorsHandler);
			} else {
				Client.get({ client: $routeParams.clientId, sites: true, site_users: true }, function (response) {
					$ClientsManager.setClient(response.data);
					$ClientsManager.setClientType('client');
				}, ErrorsHandler);
			}
		}
	});

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

	$scope.customerSelected = function (ev, datum) {

		if (datum.type == 'client') {

			// We need to retrieve the client
			Client.get({ client: datum.data.id, site_users: true }, function (res) {
				if (res.success) {
					$ClientsManager.setClient(res.data);
					$ClientsManager.setClientType('client');
				}

			}, ErrorsHandler);
		} else {

			// We will retrieve a customer
			Customer.get({ customer: datum.data.id }, function (res) {
				if (res.success) {
					$ClientsManager.setClient(res.data);
					$ClientsManager.setClientType('customer');
				}

			}, ErrorsHandler);
		}
	};

	$scope.submitButtonText = function () {
		return ($ClientsManager.isSelected()) ? 'Update' : 'Create';
	};

	$scope.focusSearch = function () {
		angular.element('#client_search').focus();
	};

	//Open de form to add a new client or customer
	$scope.addCustomer = function (type) {
		$scope.customerModal = $uibModal.open({
			templateUrl: 'clients/modals/new-customer.html',
			controller: 'AddCustomerCtrl',
			size: 'lg'
		});

		$scope.customerModal.opened.then(function () {
			// Fake change route
			$routeParams.customerId = null;
			$rootScope.$broadcast('$routeChangeSuccess');
		});
	};

	$scope.editCustomer = function () {
		$scope.customerModal = $uibModal.open({
			templateUrl: 'clients/modals/new-customer.html',
			controller: 'EditCustomerCtrl',
			size: 'lg',
			resolve: {
				client: function () {
					return $ClientsManager.getClient();
				}
			}
		});

		$scope.customerModal.result.then(function (client) {
			// Update the client manager with the updated client data
			$ClientsManager.setClient(client);
			$ClientsManager.setClientType(client.type);
		});
	};

	$scope.isPage = function (page) {
		return ($location.path().indexOf(page) != -1);
	};

	$scope.noTypeSelected = function () {
		return ($location.path() == '/bookings' || $location.path().indexOf('/bookings/client') != -1 || $location.path().indexOf('/bookings/customer') != -1);
	};

	$scope.formatTabUrl = function (url) {

		// Inject the client type and client id
		if ($routeParams.clientId && $routeParams.clientType)
			return '#bookings/' + url + '/' + $routeParams.clientType + '/' + $routeParams.clientId;

		return '#bookings/' + url;
	};

}]);
