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

var CalendarMojoService = Class.create( {
  initialize: function() {
  },

	// App 
	getStartOfWeek: function(callback, appController) {
		return appController.serviceRequest(CalendarMojoService.identifier, {
			method: 'getStartOfWeek',
			parameters: {},
			onSuccess: callback
		});
	},
	
	// First use flag is now stored in cookie. See app-assistant.js...
	
	/*
	isFirstUse: function(callback, failureCallback) {
		return new Mojo.Service.Request(CalendarMojoService.identifier, {
			method: 'isFirstUse',
			parameters: {},
			onSuccess: callback,
			onFailure: failureCallback
		});
	},
	
	setFirstUseToFalse: function(callback) {
		return new Mojo.Service.Request(CalendarMojoService.identifier, {
			method: 'setFirstUseToFalse',
			parameters: {},
			onSuccess: callback,
		});
	},
	*/
	
	getCalendarPrefs: function(callback, appController) {
		return appController.serviceRequest(CalendarMojoService.identifier, {
			method: 'getCalendarPrefs',
			parameters: {subscribe: true},
			onSuccess: callback
		});
	},
	
	setCalendarPrefs: function(prefs, callback, appController) {
		if (appController == undefined) {
			return new Mojo.Service.Request(CalendarMojoService.identifier, {
				method: 'setCalendarPrefs',
				parameters: {
					startOfWeek: prefs.startOfWeek,
					startTimeOfDay: prefs.startTimeOfDay,
					endTimeOfDay: prefs.endTimeOfDay,
					alarmSoundOn: prefs.alarmSoundOn,
					defaultEventDuration: prefs.defaultEventDuration,
					defaultCalId: prefs.defaultCalId,
					autoDefaultCalId: prefs.autoDefaultCalId,
					defaultEventReminder: prefs.defaultEventReminder,
					defaultAllDayEventReminder: prefs.defaultAllDayEventReminder,
					userChangedstartOfWeek:prefs.userChangedstartOfWeek,
					ringtonePath:prefs.ringtonePath,
					ringtoneName:prefs.ringtoneName
				},
				onSuccess: callback
			});
		} else {
			return appController.serviceRequest(CalendarMojoService.identifier, {
				method: 'setCalendarPrefs',
				parameters: {
					startOfWeek: prefs.startOfWeek,
					startTimeOfDay: prefs.startTimeOfDay,
					endTimeOfDay: prefs.endTimeOfDay,
					alarmSoundOn: prefs.alarmSoundOn,
					defaultEventDuration: prefs.defaultEventDuration,
					defaultCalId: prefs.defaultCalId,
					autoDefaultCalId: prefs.autoDefaultCalId,
					defaultEventReminder: prefs.defaultEventReminder,
					defaultAllDayEventReminder: prefs.defaultAllDayEventReminder,
					userChangedstartOfWeek:prefs.userChangedstartOfWeek,
					ringtonePath:prefs.ringtonePath,
					ringtoneName:prefs.ringtoneName,

				},
				onSuccess: callback
			});
		}
	},
	
	setCalendars: function(calendarArr, callback) {
		
		return new Mojo.Service.Request(CalendarMojoService.identifier, {
				method: 'setCalendars',
				parameters: {
					calendars: calendarArr
				},
				onSuccess: callback
			});
	},
	
	// Month View
	getBusyDays: function(calendar, startDate, endDate, callback, sceneController) {
		var url = CalendarMojoService.identifier;
		return sceneController.serviceRequest(url, {
			method: 'getBusyDays',
			parameters: {calendarId: calendar, startDate: startDate, endDate: endDate, subscribe: true},
			onSuccess: callback
		});
	},
	
	getEventsCalendarInjector: function(calendar, callback, response) {
		//Mojo.Log.info('getEventsCalendarInjector');
		
		response.days.each(function(day){
			
			day.allDayEvents.each(function(allday){
				if (allday.calendarId) {
					allday.calendarColor = getCalendarsManager().getCalColorStyle(allday.calendarId);
					allday.readonly = getCalendarsManager().isCalendarReadOnly(allday.calendarId);
				} else
					allday.calendarColor = 'cal-color-blue';
			}, this);
			
			day.events.each(function(event){
				if (event.calendarId) {
					event.calendarColor = getCalendarsManager().getCalColorStyle(event.calendarId);
					event.readonly = getCalendarsManager().isCalendarReadOnly(event.calendarId);
					
				} else
					event.calendarColor = 'cal-color-blue';
			}, this);
			
		}, this);
		
		return callback(response);
	},
	
	//this has been merged into the getEvent call
	/*getEventAttendeesInjector: function(callback, response) {
		//need to add organizer and num attendees parameters to response
      //Mojo.Log.info("response : %j",response);
		//set the organizer here.
		  response.attendees.each(function(thing){  	
			if (thing.organizer) {
				//console.info(Object.toJSON(thing));
				response.organizer = thing.name;				
			}		
		});
		
		return callback(response);
	},*/
	
	getEventInjector: function(callback, response) {
		if (response.calendarId) {
			response.calendarColor = getCalendarsManager().getCalColorStyle(response.calendarId);
			}
		else
			response.calendarColor = 'cal-color-blue';
		getRecurrenceRule().extractExdateFromRRule(response);
		  response.attendees.each(function(thing){  	
		 
			if (thing.organizer) {
				//console.info(Object.toJSON(thing));
				response.attendees.organizer = thing.name;	
						
			}	
		});
		return callback(response);
	},
	
	// Day View
	getEventChange: function(callback, sceneController) {
		var serviceParams = {subscribe: true};
		return sceneController.serviceRequest(CalendarMojoService.identifier, {
			method: 'getEventChange',
			parameters: serviceParams,
			onSuccess: callback
		});
	},
	
	getEvents: function(calendar, startDate, endDate, callback, sceneController, failure, params) {
		var serviceParams = {calendarId: calendar, startDate: startDate, endDate: endDate, subscribe: false};
		if (params)
			Object.extend(serviceParams, params);
		
		if(Mojo.Host.current === Mojo.Host.mojoHost) {
			// Mock service response.
			callback.wrap(this.getEventsCalendarInjector.bind(this, calendar)).defer(
					{"days": [
						{"date": 1260691200000, "events": [], "allDayEvents": [], "freeTimes": [], "busyTimes": []},
						{"date": 1260777600000, "events": [
									{"start": 1260810000000, "subject": "E2", "end_decimal": 1000, "alarm": "-PT15M", "note": "Hghjgdkiexjld", 
										"isRecurringForever": false, "start_decimal": 900, "location": "", "overlap_count": 1, "calendarId": "id40681930227720", 
										"overlap_index": 0, "id": "41781441855492-1260810000000-1260813600000", "end": 1260813600000, "allDay": false},
									{"start": 1260828000000, "subject": "E3", "end_decimal": 1500, "alarm": "-PT15M", "note": "Ggbhekujixjdd",
										"isRecurringForever": false, "start_decimal": 1400, "location": "", "overlap_count": 1, "calendarId": "id40681930227720",
										 "overlap_index": 0, "id": "41781441855493-1260828000000-1260831600000", "end": 1260831600000, "allDay": false}
								],
								"allDayEvents": [],
								"freeTimes": [{"start_decimal": 1000, "end_decimal": 1400, "duration": 400}],
								"busyTimes": []
						},

					 	{"date": 1260864000000, "events": [], "allDayEvents": [], "freeTimes": [], "busyTimes": []}
						]}
					);
			
			return {};
		}
		
		return sceneController.serviceRequest(CalendarMojoService.identifier, {
			method: 'getEvents',
			parameters: serviceParams,
			onSuccess: callback.wrap(this.getEventsCalendarInjector.bind(this, calendar)),
			onFailure: failure
		});
	},
	
	// Event Details
	eventDetails: function(id, callback, sceneController) {
		var url = CalendarMojoService.identifier + '/mock_calendar_service';
		return sceneController.serviceRequest(url, {
			method: 'eventDetails',
			parameters: {id: id, subscribe: true},
			onSuccess: callback
		});
	},
  
	formatEventInfo: function(start, end, allDay,timeformat, callback, sceneController) {
		var url = CalendarMojoService.identifier + '/formatter';
		return sceneController.serviceRequest(url , {      
			method: 'formatEventInfo',
			parameters: {start: start, end: end, allDay: allDay, timeformat: timeformat, subscribe: true},
			onSuccess: callback
		});
	},

	formatRepeatStrings: function(start, repeatList, callback, sceneController) {
		Mojo.Log.info('service call formatRepeatStrings');
		var url = CalendarMojoService.identifier + '/formatter';
		return sceneController.serviceRequest(url , {      
			method: 'formatRepeatStrings',
			parameters: {
				start: start,
				list: repeatList
			},
			onSuccess: callback
		});
	},
	formatAlarmStrings: function(alarmlist, callback, sceneController) {
		var url = CalendarMojoService.identifier + '/formatter';
		return sceneController.serviceRequest(url , {      
			method: 'formatAlarmStrings',
			parameters: alarmlist,
			onSuccess: callback
		});
	},

	formatEventDuration: function(start, end, allDay, callback, sceneController) {
		var url = CalendarMojoService.identifier + '/formatter';
		return sceneController.serviceRequest(url , {      
			method: 'formatEventDuration',
			parameters: {start: start, end: end, allDay: allDay},
			onSuccess: callback
		});
	},

	setEvent: function(targetEvent, callback, sceneController, failure) {
		if(!targetEvent.rrule || targetEvent.rrule=="")
			targetEvent.endValidity = 0;
		else if(targetEvent.rrule && targetEvent.rrule!="" && targetEvent.isRecurringForever ==true)
		    targetEvent.endValidity = "Long.MAX_VALUE";
				
		if (sceneController) {
			return sceneController.serviceRequest(CalendarMojoService.identifier, {
				method: 'setEvent',
				parameters: targetEvent,
				onSuccess: callback,
				onFailure: failure
			});
		} else {
			return new Mojo.Service.Request(CalendarMojoService.identifier, {
				method: 'setEvent',
				parameters: targetEvent,
				onSuccess: callback,
				onFailure: failure
			});
		}
		
	},
	updateEvent: function(targetEvent, callback, sceneController, failure) {
		
		return sceneController.serviceRequest(CalendarMojoService.identifier, {
			method: 'updateEvent',
			parameters: targetEvent,
			onSuccess: callback,
			onFailure: failure
		});
	},

	getEvent: function(id, callback,failureCallback, sceneController) {
		return sceneController.serviceRequest(CalendarMojoService.identifier, {      
			method: 'getEvent',
			parameters: {id: id, subscribe: false},
			onSuccess: callback.wrap(this.getEventInjector.bind(this)),
			onFailure: failureCallback
		});
	},
	//getEventAttenees has been merged into the get Event call
	/*getEventAttendees:function(id,callback,sceneController){
			return sceneController.serviceRequest(CalendarMojoService.identifier, {      
			method: 'getEventAttendees',
			parameters: {id: id, subscribe: false},
			//onSuccess: callback
			onSuccess: callback.wrap(this.getEventAttendeesInjector.bind(this))
		});
	},*/
	
	deleteEvent: function(id, series,date,callback, sceneController) {
		return sceneController.serviceRequest(CalendarMojoService.identifier, {      
			method: 'deleteEvent',
			parameters: {id: id,series:series,date:date},
			onSuccess: callback
		});
	},
	
	getMonth: function(startDate, endDate, callback, sceneController) {
		return sceneController.serviceRequest(CalendarMojoService.identifier, {
			method: 'getMonth',
			parameters: {startDate: startDate, endDate: endDate},
			onSuccess: callback
		});
	},
	
	getDay: function(dayDate, callback, sceneController) {
		return sceneController.serviceRequest(CalendarMojoService.identifier, {
			method: 'getDay',
			parameters: {dayDate: dayDate},
			onSuccess: callback
		});
	},
	
    getOccurenceCount: function(start, rrule,endValidity,callback, sceneController){
	  		
			var url = CalendarMojoService.identifier;
			return sceneController.serviceRequest(url , {      
				method: 'getOccurenceCount',
				parameters: {startTimestamp:start,rrule:rrule,endValidity:endValidity},
				onSuccess: callback
				
			});
	  },
	
	getEmailAccountId: function(sceneController, domain, login, callback, failureCallback) {
		return sceneController.serviceRequest(CalendarMojoService.identifier, {      
			method: 'getEmailAccountId',
			parameters: {accountDomain: domain, accountLogin: login},
			onSuccess: callback,
			onFailure: failureCallback
		});
	},
	
	// *** PREFERENCES ***
	getCalendarsForSyncAccount: function(id, callback, sceneController) {
		return sceneController.serviceRequest(CalendarMojoService.identifier, {      
			method: 'getCalendarsForSyncAccount',
			parameters: {id: id, subscribe: true},
			onSuccess: callback
		});
	},
	
	getCalendarsForAccountList: function(idList,callback,sceneController){
		return sceneController.serviceRequest(CalendarMojoService.identifier, {      
			method: 'getCalendarsForAccountList',
			parameters: {accountList: idList, subscribe: true},
			onSuccess: callback
		});
	},
	
	isEventDirty:function(oldEvent,newEvent){
  	Mojo.Log.info("in check for isEventDirty");
	var recurrenceRule = getRecurrenceRule();	
	if (oldEvent == undefined) {
		Mojo.Log.info("old event is undefined");
		return true;
	}
	if (oldEvent.subject != newEvent.subject) {	
		Mojo.Log.info("subject is dirty");
		newEvent.onlyRepeatChanged =false;
		return true;
		
	}
	if (oldEvent.location != newEvent.location) {
		newEvent.onlyRepeatChanged =false;
		Mojo.Log.info("location is dirty");
		return true;
		
	}
	if (oldEvent.allDay != newEvent.allDay) {
		newEvent.onlyRepeatChanged =false;
		Mojo.Log.info("allday is dirty %s , %s"),newEvent.allDay,oldEvent.allDay;
		return true;
		
	}
	if (oldEvent.calendarId != newEvent.calendarId) {
		newEvent.onlyRepeatChanged =false;
		Mojo.Log.info("calendarid is dirty");
		return true;
		
	}
	

	if (oldEvent.startTimestamp != newEvent.startTimestamp) {
		newEvent.onlyRepeatChanged =false;
		Mojo.Log.info("starttimestamp is dirty");
		return true;
	}
	if (oldEvent.endTimestamp != newEvent.endTimestamp) {
		newEvent.onlyRepeatChanged =false;
		Mojo.Log.info("endtimestamp is dirty");
		return true;
	}
	if (oldEvent.alarm != newEvent.alarm && 
	    !( oldEvent.alarm ==undefined && newEvent.alarm=='none')) {
		Mojo.Log.info("alarm is dirty");
		newEvent.onlyRepeatChanged =false;
		return true;
	}
	if (oldEvent.note != newEvent.note) {
		Mojo.Log.info("note is dirty");
		newEvent.onlyRepeatChanged =false;
		return true;
	}
	if (oldEvent.endValidity != newEvent.endValidity) {
		Mojo.Log.info("endvalidity is dirty"+" "+ oldEvent.endValidity+ " "+newEvent.endValidity);
		return true;
	}
	if(oldEvent.rrule != newEvent.rrule){
		Mojo.Log.info("rrule is dirty"+ " "+oldEvent.rrule+ " "+newEvent.rrule);
		return true;

	}
	//removing checking element by element in the rrulemodel
	//it is better to just construct the rrule string and compare it
	//to the oldEvent's rrule string. This is more accurate.

	Mojo.Log.info('event is not dirty');
		return false;
	 
		
	}
});

CalendarMojoService.identifier = 'palm://com.palm.calendar';

var FakeMojoRequest = Class.create({
  cancel: function() {
  }
});
