/**
 * BookingsOnsiteCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('BookingsOnsiteCtrl', ['$scope', '$route', '$routeParams', '$location', '_onsiteForm', '$ClientsManager', 'BookingsLocationManager', '$http', 'apiUrl', '$filter', '$timeout', 'TaskTemplatesService', function ($scope, $route, $routeParams, $location, _onsiteForm, $ClientsManager, BookingsLocationManager, $http, apiUrl, $filter, $timeout, TaskTemplatesService) {

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

	var timeRenderer = function (date) {
		var data = [];
		if (!date) date = new Date();

		// var current_date = $filter('date')(date, 'yyyy-MM-dd');

		for (var i = 0; i < 24; i++) {
			for (var j = 0; j < 60; j += 15) {
				var h = (i < 10) ? '0' + i : i;
				var m = (j < 10) ? '0' + j : j;
				data.push({ label: h + ':' + m, value: h + ':' + m + ':00' });
			}
		}

		return data;
	};

	$scope.selectedDate = null;
	$scope.times = timeRenderer();

	$scope.data = _onsiteForm.data;

	// working with the shared service managers
	$scope.clientManager = $ClientsManager;
	$scope.locationManager = BookingsLocationManager;

	$scope.form = _onsiteForm;
	$scope.routeParams = $routeParams;

	// added by nadeem 13.2.17 - if the user use the add task to project button
	// then this will pass the project id forward to the back-end
	// the crated task will then be correctly associated with the correct project
	if (typeof ($scope.$parent.projectId != 'undefined')) {
		$scope.data.project_id = $scope.$parent.projectId;
	}

	/**
	 * Bind the task templates typeahead remote options to the scope.
	 *
	 * @object
	 */
	$scope.templatesRemoteOptions = TaskTemplatesService;


	/**
	*Initialize the start and end date when loading the page
	*/
	$scope.start_time = '09:00:00';
	$scope.end_time = '10:00:00';
	$scope.onsite_start = moment().hours(9).minutes(0).seconds(0);
	$scope.onsite_end = moment().hours(10).minutes(0).seconds(0);


	// We need to call $scope.$apply() when we load events
	// except for the first time when the page is loaded.
	// This variable checks to see if it was loaded already.
	var EventsLoaded = false;


	// This is the only event in the calendar that the user can edit
	$scope.newEvent = {
		title: 'New',
		start: '',
		end: '',
		allDay: false,
		editable: true
	};

	$scope.updateData = function () {
		$scope.data.onsite_start = $scope.onsite_start.format('YYYY-MM-DD HH:mm');
		$scope.data.onsite_end = $scope.onsite_end.format('YYYY-MM-DD HH:mm');
		$scope.newEvent.start = $scope.data.onsite_start;
		$scope.newEvent.end = $scope.data.onsite_end;
	};

	$scope.updateData();

	// Event sources, the events loaded from the database
	// plus the editable event
	$scope.eventSources = [
		[
			$scope.newEvent
		],
		{
			events: function (start, end, callback) {
				$scope.loadCalendarEvents(Math.round(start.getTime() / 1000), Math.round(end.getTime() / 1000), callback);
				if (EventsLoaded) {
					$scope.times = timeRenderer(start);
					$scope.updateSelectedTime(start, end);
					//$scope.$apply();
				}
				EventsLoaded = true;
			},
			editable: false
		}
	];

	// ------------------------------------------------------------------------
	//
	//	WATCHERS AND EVENT LISTENERS BELOW -->
	//
	// ------------------------------------------------------------------------
	$scope.$watch('data.site_user_id', function () {
		$scope.data.direct_dial = BookingsLocationManager.getUserDDI($scope.data.site_user_id);
	});

	$scope.$watch('data.site_id', function () {
		$scope.data.direct_dial = BookingsLocationManager.getUserDDI($scope.data.site_user_id);
	});

	$scope.$watch('data.title', function () {
		if (typeof $scope.data.title == 'undefined') return false;
		$scope.newEvent.title = $scope.data.title;
	});

	$scope.$watch('start_time', function (value) {
		$scope.updateStartTime(value);
	}, true);

	$scope.$watch('end_time', function (value) {
		$scope.updateEndTime(value);
	}, true);

	$scope.$watch('newEvent.allDay', function (value) {
		if (value)
			$scope.newEvent.allDay = false;
		$scope.fullCalendar.fullCalendar('render');
	});

	$scope.$watch('selectedDate', function (value) {

		if (value) {
			$scope.fullCalendar.fullCalendar('gotoDate', value);
			$('.datepicker').hide();
		}
	});
	// ------------------------------------------------------------------------
	//
	//	FUNCTIONS BELOW THIS LINE -->
	//
	// ------------------------------------------------------------------------

	$scope.save = _onsiteForm.save;

	$scope.loadCalendarEvents = function (start, end, callback) {
		$http.get(apiUrl('calendar'), {
			params: {
				start_date: start,
				end_date: end
			}
		}).success(function (response) {
			callback(response);
		});
	};

	$scope.eventResize = function (event, dayDelta, minuteDelta, revertFunc) {
		$scope.end_time = moment(event.end).format('HH:mm:ss');
	};

	$scope.eventDrop = function (event) {
		$scope.start_time = moment(event.start).format('HH:mm:ss');
		$scope.end_time = moment(event.end).format('HH:mm:ss');
	};

	// ------------------------------------------------------------------------
	//
	//	Calendar data goes here at the end after all functions have been defined
	//
	// ------------------------------------------------------------------------
	$scope.calendar = {
		editable: false,
		defaultView: 'agendaDay',
		firstDay: 1,
		firstHour: 9,
		hiddenDays: [0],
		axisFormat: 'HH:mm',
		timeFormat: {
			agenda: 'HH:mm{ - HH:mm}'
		},
		header: {
			left: 'today',
			center: 'title',
			right: 'prev, next, agendaDay, agendaWeek, month'
		},
		eventResize: $scope.eventResize,
		eventDrop: $scope.eventDrop
	};

	$scope.updateSelectedTime = function (start, end) {
		var start_date = moment($scope.onsite_start);
		var end_date = moment($scope.onsite_end);
		$scope.onsite_start = moment(start).hours(start_date.hours()).minutes(start_date.minutes());
		$scope.onsite_end = moment(start).hours(end_date.hours()).minutes(end_date.minutes());
		$scope.updateData();

	};

	$scope.updateStartTime = function (value) {
		var start = moment(value, 'HH:mm');
		$scope.onsite_start.hours(start.hours()).minutes(start.minutes());
		$scope.updateData();
	};

	$scope.updateEndTime = function (value) {
		var end = moment(value, 'HH:mm');
		$scope.onsite_end.hours(end.hours()).minutes(end.minutes());
		$scope.updateData();
	};

	$timeout(function () {
		$scope.data.title = '';
		$scope.$apply();
	}, 10);

}]);
