/**
 * QuickNewTaskCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('QuickNewTaskCtrl', ['$scope', 'User', 'Tasks', 'ErrorsHandler', '$q', 'Client', 'Customer', '$AuthUser', 'TaskTypes', function ($scope, User, Tasks, ErrorsHandler, $q, Client, Customer, $AuthUser, TaskTypes) {

	$scope.tokens = [];

	var dates = [
		{ name: 'Today', value: moment() },
		{ name: 'Tommorrow', value: moment().add('days', 1) },
		{ name: moment().add('days', 2).format('dddd - DD/MM/YYYY'), value: moment().add('days', 2) },
		{ name: moment().add('days', 3).format('dddd - DD/MM/YYYY'), value: moment().add('days', 3) },
		{ name: moment().add('days', 4).format('dddd - DD/MM/YYYY'), value: moment().add('days', 4) },
		{ name: moment().add('days', 5).format('dddd - DD/MM/YYYY'), value: moment().add('days', 5) },
		{ name: moment().add('days', 6).format('dddd - DD/MM/YYYY'), value: moment().add('days', 6) },
		{ name: moment().add('days', 7).format('dddd - DD/MM/YYYY'), value: moment().add('days', 7) }
	],
		times = [];

	for (var i = 0; i < 24; i++) {
		for (var j = 0; j < 60; j += 15) {
			var time = (i < 10) ? '0' + i : i;
			time += ':';
			time += (j < 10) ? '0' + j : j;
			times.push(time);
		}
	}

	$scope.tags = {
		task: TaskTypes.getType('support')
	};

	$scope.learn = {
		title: 'Learn more',
		container: 'body',
		content: 'Use the following symbols as options when making a booking: <br /> ' +
			'<strong>@</strong> - search and assign the task to a user <br />' +
			'<strong>#</strong> - search and assign the task to a customer <br />' +
			'<strong>^</strong> - select the type of task (ie. repair, remote support) <br />' +
			'<br /> <strong>The following are only required for onsite</strong> <br />' +
			'<strong>$</strong> - select a date <br />' +
			'<strong>!</strong> - select a time <br />' +
			'<br /> <strong>Other useful tips & tricks</strong> <br />' +
			'To separate the description from the title, simply leave two new lines (ie. press ENTER twice). The top bit will be the title and the bottom bit will be the description. <br /><br /> Easy, right?'
	};

	$scope.searchUsers = function (term) {
		return User.get({ q: term, limit: 5 }, function (response) {
			$scope.users = response.data;
			return $q.when(response.data);
		}, ErrorsHandler);
	};

	$scope.tokenize = function (token, value) {
		var token = token + value;
		$scope.tokens.push(token);
		return token;
	};

	$scope.getUserRaw = function (item) {
		$scope.tags.staff = item;
		return $scope.tokenize('@', item.name);
	};

	$scope.searchCustomers = function (term) {

		var clients = Client.get({ name: term, contract: true, limit: 5 }).$promise;
		var customers = Customer.get({ name: term, limit: 5 }).$promise;

		return $q.all([clients, customers])
			.then(function (all) {
				$scope.customers = all[0].data.concat(all[1].data);
				return $q.when(all);
			});
	};

	$scope.getCustomerRaw = function (item) {
		$scope.tags.client = item;
		return $scope.tokenize('#', item.name);
	};

	$scope.searchTaskTypes = function (term) {
		$scope.taskTypes = [];
		_.each(TaskTypes.getTypes(), function (el) {
			if (el.name.toLowerCase().indexOf(term.toLowerCase()) >= 0) {
				$scope.taskTypes.push(el);
			}
		});
	};

	$scope.getTaskTypeRaw = function (item) {
		$scope.tags.task = item;
		return $scope.tokenize('^', item.name);
	};

	$scope.searchTaskTimes = function (term) {
		$scope.times = [];
		var limit = 5,
			found = 0;
		_.each(times, function (el) {
			if (found < limit && el.toLowerCase().indexOf(term.toLowerCase()) >= 0) {
				$scope.times.push(el);
				found++;
			}
		});
	};

	$scope.getTaskTimesRaw = function (item) {
		$scope.tags.time = item;
		return $scope.tokenize('!', item);
	};

	$scope.searchTaskDates = function (term) {
		$scope.dates = [];

		_.each(dates, function (el) {
			if (el.name.toLowerCase().indexOf(term.toLowerCase()) >= 0) {
				$scope.dates.push(el);
			}
		});
	};

	$scope.getTaskDatesRaw = function (item) {
		$scope.tags.date = item;
		return $scope.tokenize('$', item.name);
	};

	$scope.save = function () {
		var data = {};

		// Client field is required
		if (!$scope.tags.client) {
			alert("You need to select a customer before continuing! Use # to start the search...");
			return false;
		}

		// Onsite validations
		if ($scope.tags.task && $scope.tags.task.id == 'onsite') {
			if (!$scope.tags.date) {
				alert("You need to select a date for an onsite job. Use $ to start searching.");
				return false;
			}
			if (!$scope.tags.time) {
				alert("You need to select a start time. Use ! to start searching.");
				return false;
			}

			data['onsite_start'] = $scope.tags.date.value.format("YYYY-MM-DD") + ' ' + $scope.tags.time + ':00';
			data['onsite_end'] = moment(data['onsite_start']).add('hours', 1).format("YYYY-MM-DD HH:mm:ss");
		}

		// Grab a copy of the textarea text and
		// remove all the user filled tokens
		var originalText = $scope.newTaskTextarea;

		_.each($scope.tokens, function (el) {
			// Here we replace all the known tokens out from the text
			originalText = originalText.replace(el, '');
		});

		var splitText = originalText.split("\n\n"),
			title = splitText[0].trim()
		description = (splitText.length > 1) ? (splitText.shift() && splitText.join("\n\n").trim()) : splitText[0].trim();

		angular.extend(data, {
			client_id: $scope.tags.client.id,
			client_type: $scope.tags.client.type,
			type: $scope.tags.task ? $scope.tags.task.id : TaskTypes.getType('support').id,
			title: title,
			problem: description.replace(/\r?\n/g, "<br />"),
			assigned_to: $scope.tags.staff ? $scope.tags.staff.id : null
		});

		Tasks.save(
			data,
			function (response) {
				$scope.task = response;
				$scope.newTaskTextarea = '';
				$scope.tags = {
					task: TaskTypes.getType('support')
				};
			},
			ErrorsHandler);
	};

}]);
