/**
 * ChangeDatesCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('ChangeDatesCtrl', ['$scope', '$uibModalInstance', 'data', '$filter', 'Tasks', 'ErrorsHandler', 'Messenger', function ($scope, $uibModalInstance, data, $filter, Tasks, ErrorsHandler, Messenger) {

	$scope.data = data;
	$scope.times = [];

	$scope.data.start = moment(data.onsite_start).toDate();
	$scope.data.end = moment(data.onsite_end).toDate();
	$scope.data.start_time = moment(data.onsite_start).format('HH:mm');
	$scope.data.end_time = moment(data.onsite_end).format('HH:mm');

	var addPadding = function (i) {
		return (i < 10) ? '0' + i : i;
	};

	// Build the hours and minutes
	for (var i = 0; i < 24; i++) {
		for (var j = 0; j < 60; j += 15) {
			$scope.times.push(addPadding(i) + ':' + addPadding(j));
		}
	}

	$scope.save = function () {
		data.onsite_start = $filter('date')(new Date($scope.data.start), 'yyyy-MM-dd') + ' ' + $scope.data.start_time + ':00';
		data.onsite_end = $filter('date')(new Date($scope.data.end), 'yyyy-MM-dd') + ' ' + $scope.data.end_time + ':00';

		if (moment(data.onsite_start).valueOf() > moment(data.onsite_end).valueOf()) {
			alert('The start date should be lower than the end date');
			return false;
		}

		Tasks.update(data, function (response) {
			Messenger("Task updated succesfully!");
			$uibModalInstance.close(response);
		}, ErrorsHandler);
	};

	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};

}]);
