/* Copyright 2009 Palm, Inc.  All rights reserved. */

var ReminderManager = Class.create ({
	
	initialize: function() {
		Mojo.Log.info("$$$$$$$$ Reminder-manager intialize:start ");
		
		this.observers = new Hash();
		this.reminders = [];
		
		this.eventChangeRequest = new Mojo.Service.Request('palm://com.palm.calendar', {
					                    method: 'getEventChange',
					                    parameters: {subscribe: true},
										onSuccess: this.getEventChangeCallback.bind(this)
					                	});
		
		Mojo.Log.info("$$$$$$$$ Reminder-manager intialize:end ");
	},
	
	cleanup: function() {
		Mojo.Log.info("$$$$$$$$ Reminder-manager cleanup: start ");
		this.eventChangeRequest.cancel();
		Mojo.Log.info("$$$$$$$$ Reminder-manager cleanup: end ");
	},
	
	getEventChangeCallback: function(response) {
		Mojo.Log.info("$$$$$$$$ Reminder-manager getEventChangeCallback:start ");
		if (response.changed) {
			// Get the event for each reminder since it may have changed
		    window.setTimeout(function() {
				this.requests = [];
				for (var i = 0; i < this.reminders.length; i++) {
					Mojo.Log.info("$$$$$$$$ Reminder-manager getEventChangeCallback : getting Event, "+this.reminders[i].id);
					this.requests.push(new Mojo.Service.Request('palm://com.palm.calendar', {      
						method: 'getEvent',
						parameters: {id: this.reminders[i].id, subscribe: false},
						onSuccess: this.getEventCallback.bind(this, this.reminders[i]),
						onFailure: this.getEventFailed.bind(this, this.reminders[i])
					}));
				}
		    }.bind(this), 0.01);
		}
		Mojo.Log.info("$$$$$$$$ Reminder-manager getEventChangeCallback:end ");
	},
	
	getEventCallback: function(reminder, response) {
		Mojo.Log.info("$$$$$$$$ Reminder-manager getEventCallback:start ");
		if ((response.alarm == undefined) ||
			(response.alarm == "none")  || 
			(response.reminderLongId !=reminder.id))
		{
			Mojo.Log.info("$$$$$$$$ Reminder-manager getEventCallback: removingReminder, "+ reminder.id);
			this.removeReminder(reminder.id);
			return;
		}
		Mojo.Log.info("$$$$$$$$ Reminder-manager getEventCallback: updatingReminder, "+ reminder.id);
		reminder.subject = response.subject;
		reminder.location = response.location;
		reminder.isAllDay = response.allDay;
		reminder.subtitle = this.getReminderSubtitle(reminder);
		this.notifyObservers();
		
		Mojo.Log.info("$$$$$$$$ Reminder-manager getEventCallback:end ");
	},
	
	getEventFailed: function(reminder, response) {
		Mojo.Log.info("$$$$$$$$ Reminder-manager getEventFailed: start "+ reminder.id);
		this.removeReminder(reminder.id);
		Mojo.Log.info("$$$$$$$$ Reminder-manager getEventFailed: end "+ reminder.id);
	},
	
	// If reminder already exists move it to the end of the list so it becomes the most recent, 
	// otherwise just add it to the list.
	updateReminder: function(eventId, subject, location, attendees, isAllDay, emailAccountId) {
		Mojo.Log.info("$$$$$$$$ Reminder-manager updateReminder: start, "+ eventId);
		
		for (var i = 0; i < this.reminders.length; i++) {
			if(eventId == this.reminders[i].id){
				
				var reminder = this.reminders.splice(i, 1);
				Mojo.Log.info("$$$$$$$$ Reminder-manager updateReminder: pushing event to be the most recent, "+reminder[0].id);
				this.reminders.push(reminder[0]);
				this.notifyObservers();
				return;
			}
		}
		Mojo.Log.info("$$$$$$$$ Reminder-manager updateReminder: adding reminder to reminderManager, "+eventId);
		this.addReminder(eventId, subject, location, attendees, isAllDay, emailAccountId);
		Mojo.Log.info("$$$$$$$$ Reminder-manager updateReminder: end, "+ eventId);
	},
	
	addReminder: function(eventId, subject, location, attendees, isAllDay, emailAccountId) {
		Mojo.Log.info("$$$$$$$$ Reminder-manager addReminder: start, "+eventId);
		var reminder;
		var idModel = parseFromId(eventId);
		reminder = {
			id: eventId,
			subject: subject,
			location: location,
			time: idModel.start,
			duration: idModel.end - idModel.start,
			subtitle: null,
			attendees: attendees,
			isAllDay: isAllDay,
			emailAccountId: emailAccountId,
			userClosed: false,
			scheduleStartTime: true
		}		
		reminder.subtitle = this.getReminderSubtitle(reminder);
		this.reminders.push(reminder);
		this.notifyObservers();
		Mojo.Log.info("$$$$$$$$ Reminder-manager addReminder: end, "+eventId);
	},
	
	removeReminder: function(eventId) {
		Mojo.Log.info("$$$$$$$$ Reminder-manager removeReminder: start");
		for (var i = 0; i < this.reminders.length; i++) {
			if (eventId == this.reminders[i].id) {
				Mojo.Log.info("$$$$$$$$ Reminder-manager removeReminder: matched an event in reminder manager, removing "+eventId);
				this.removeSchedulerTask(this.reminders[i]);
				this.reminders.splice(i, 1);
				this.notifyObservers();
				return;
			}
		}
		Mojo.Log.info("$$$$$$$$ Reminder-manager removeReminder: end");
	},
	
	removeAllReminders: function() {
		Mojo.Log.info("$$$$$$$$ Reminder-manager removeAllReminders: start");
		for (var i = 0; i < this.reminders.length; i++) {
			this.removeSchedulerTask(this.reminders[i]);
		}
		this.reminders = [];
		this.notifyObservers();
		Mojo.Log.info("$$$$$$$$ Reminder-manager removeAllReminders: end");
	},
	
	getNumReminders: function() {
		return this.reminders.length;
	},
	
	getMostRecentReminder: function() {
		return this.reminders.last();
	},
	
	getAllReminders: function() {
		return this.reminders.clone();
	},
	
	serviceRequestError: function(response) {
		console.error("Error: ReminderManager service request: %s",response);
	},
	
	getReminder: function(eventId) {
		Mojo.Log.info("$$$$$$$$ Reminder-manager getReminder: start, "+eventId);
		var reminder = null;
		this.reminders.each(function(r) {
			if (r.id == eventId) {
				Mojo.Log.info("$$$$$$$$ Reminder-manager getReminder: Matched a reminder");
				reminder = r;
			}
		});
		Mojo.Log.info("$$$$$$$$ Reminder-manager getReminder: end, "+eventId);
		return reminder;
	},
	
	getReminderSubtitle: function(reminder) {
		var templateModel = {};
		
		if (reminder.time) {
			var eventDate = new Date(reminder.time).clearTime();
			if (eventDate.equals(new Date().clearTime())) {
				templateModel.day = $L('Today');
			} else if (eventDate.equals(new Date().addDays(-1).clearTime())) {
				templateModel.day = $L('Yesterday');
			} else if (eventDate.equals(new Date().addDays(1).clearTime())) {
				templateModel.day = $L('Tomorrow');
			} else {
				templateModel.day = Mojo.Format.formatDate(eventDate, {date: "short"}); // Localize this date format string
			}
			if (getTimeFormat() == "HH12") {
		  	templateModel.time = Mojo.Format.formatDate(new Date(reminder.time), 'h:mma').toLowerCase();
		  } else {
				templateModel.time = Mojo.Format.formatDate(new Date(reminder.time), 'H:mm');
			}
		}
		
		var template = null;
		
		if (reminder.location) {
			templateModel.location = reminder.location;
			if (reminder.isAllDay)
				template = new Template($L("#{day} at #{location}"));
			else
				template = new Template($L("#{day} #{time} at #{location}"));
		} else {
			if (reminder.isAllDay)
				template = new Template($L("#{day}"));
			else
				template = new Template($L("#{day} #{time}"));
		}
		
		return template.evaluate(templateModel);
	},
	
	removeSchedulerTask: function(reminder) {
		Mojo.Log.info("$$$$$$$$ Reminder-manager removeSchedulerTask: start, "+reminder.id);
		
		Mojo.Log.info("$$$$$$$$ Reminder-manager removeSchedulerTask: removeTask: calendar-snooze-" + reminder.id );
		new Mojo.Service.Request('palm://com.palm.taskScheduler', {
					                    method: 'removeTask',
					                    parameters: {key: 'calendar-snooze-' + reminder.id}
					                	});
		
		Mojo.Log.info("$$$$$$$$ Reminder-manager removeSchedulerTask: removeTask: calendar-alarmclose-" + reminder.id );
		new Mojo.Service.Request('palm://com.palm.taskScheduler', {
					                    method: 'removeTask',
					                    parameters: {key: 'calendar-alarmclose-'+reminder.id}
					                	});								
												
		Mojo.Log.info("$$$$$$$$ Reminder-manager removeSchedulerTask: removeTask: calendar-event-" + reminder.id );
		new Mojo.Service.Request('palm://com.palm.taskScheduler', {
					                    method: 'removeTask',
					                    parameters: {key: 'calendar-event-'+reminder.id}
					                	});
																		
		Mojo.Log.info("$$$$$$$$ Reminder-manager removeSchedulerTask: end "+reminder.id);
	},
	
	// OBSERVERS
	
	observeReminders: function(sceneName, sceneController) {
		Mojo.Log.info("$$$$$$$$ Reminder-manager observeReminders: start");
//		Mojo.Log.info('reminder-manager: observeReminders ');
		this.observers.set(sceneName, sceneController);
		Mojo.Log.info("$$$$$$$$ Reminder-manager observeReminders: end");
	},
	
	stopObservingReminders: function(sceneName) {
		Mojo.Log.info("$$$$$$$$ Reminder-manager stopObservingReminders: start");
//		Mojo.Log.info('reminder-manager: stopObservingReminders ');
		this.observers.unset(sceneName);
		Mojo.Log.info("$$$$$$$$ Reminder-manager stopObservingReminders: end");
	},
	
	notifyObservers: function() {
		Mojo.Log.info("$$$$$$$$ Reminder-manager notifyObservers: start");
//		Mojo.Log.info('reminder-manager: notifyObservers ');
		this.observers.each(function(elementPair) {
			var sceneName = elementPair.key;
			var sceneController = elementPair.value;
			if (sceneController != null) 
				sceneController.remindersUpdated();
		});
		Mojo.Log.info("$$$$$$$$ Reminder-manager notifyObservers: end");
	}
	
});
