/***********************************************************************
 *
 Copyright © 1995 - 1998, 3Com Corporation or its subsidiaries ("3Com").  
 All rights reserved.
   
 This software may be copied and used solely for developing products for 
 the Palm Computing platform and for archival and backup purposes.  Except 
 for the foregoing, no part of this software may be reproduced or transmitted 
 in any form or by any means or used to make any derivative work (such as 
 translation, transformation or adaptation) without express written consent 
 from 3Com.

 3Com reserves the right to revise this software and to make changes in content 
 from time to time without obligation on the part of 3Com to provide notification 
 of such revision or changes.  
 3COM MAKES NO REPRESENTATIONS OR WARRANTIES THAT THE SOFTWARE IS FREE OF ERRORS 
 OR THAT THE SOFTWARE IS SUITABLE FOR YOUR USE.  THE SOFTWARE IS PROVIDED ON AN 
 "AS IS" BASIS.  3COM MAKES NO WARRANTIES, TERMS OR CONDITIONS, EXPRESS OR IMPLIED, 
 EITHER IN FACT OR BY OPERATION OF LAW, STATUTORY OR OTHERWISE, INCLUDING WARRANTIES, 
 TERMS, OR CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND 
 SATISFACTORY QUALITY.

 TO THE FULL EXTENT ALLOWED BY LAW, 3COM ALSO EXCLUDES FOR ITSELF AND ITS SUPPLIERS 
 ANY LIABILITY, WHETHER BASED IN CONTRACT OR TORT (INCLUDING NEGLIGENCE), FOR 
 DIRECT, INCIDENTAL, CONSEQUENTIAL, INDIRECT, SPECIAL, OR PUNITIVE DAMAGES OF 
 ANY KIND, OR FOR LOSS OF REVENUE OR PROFITS, LOSS OF BUSINESS, LOSS OF INFORMATION 
 OR DATA, OR OTHER FINANCIAL LOSS ARISING OUT OF OR IN CONNECTION WITH THIS SOFTWARE, 
 EVEN IF 3COM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

 3Com, HotSync, Palm Computing, and Graffiti are registered trademarks, and 
 Palm III and Palm OS are trademarks of 3Com Corporation or its subsidiaries.

 IF THIS SOFTWARE IS PROVIDED ON A COMPACT DISK, THE OTHER SOFTWARE AND 
 DOCUMENTATION ON THE COMPACT DISK ARE SUBJECT TO THE LICENSE AGREEMENT 
 ACCOMPANYING THE COMPACT DISK.
 
 *****************************************************************************
 *
 * PROJECT:  Pilot
 * FILE:     DateAlarm.c
 * AUTHOR:	 Art Lamb: August 29, 1995
 *
 * DECLARER: Datebook
 *
 * DESCRIPTION:
 *	  This module contain the routine that handle alarms.
 *
 **********************************************************************/

#include <Pilot.h>
#include <AlarmMgr.h>
#include <FeatureMgr.h>
#include "Datebook.h"


/***********************************************************************
 *
 *	Global variables
 *
 ***********************************************************************/
extern UInt alarmSoundRepeatCount;
extern UInt alarmSoundRepeatInterval;
extern UInt alarmSound;


/***********************************************************************
 *
 *	Internal Constants
 *
 ***********************************************************************/
#define alarmDescDrawX						45
#define alarmDescDrawY						25
#define alarmDescRightMargin				10
#define alarmDescMaxLine					6
#define alarmDescMaxWidth					100


/***********************************************************************
 *
 *	Internal Structures
 *
 ***********************************************************************/

typedef struct {
	Word 		recordNum;
	ULong		alarmTime;
} PendingAlarmType;


/***********************************************************************
 *
 *	Local prototypes
 *
 ***********************************************************************/

void DBDisplayAlarm(void);

/***********************************************************************
 *
 * FUNCTION:    GetTimeOfNextAlarm
 *
 * DESCRIPTION: This routine gets the time of the next scheduled
 *              alarm from the Alarm Manager.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    the time of the next scheduled alarm, or zero if 
 *              no alarm is scheduled.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	9/1/95	Initial Revision
 *
 ***********************************************************************/
static ULong GetTimeOfNextAlarm (DWordPtr refP)
{
	UInt 			cardNo;
	LocalID 		dbID;
	ULong			alarmTime = 0;	
	DmSearchStateType searchInfo;

	DmGetNextDatabaseByTypeCreator (true, &searchInfo, 
		sysFileTApplication, sysFileCDatebook, true, &cardNo, &dbID);

	alarmTime = AlmGetAlarm (cardNo, dbID, refP);

	return (alarmTime);
}


/***********************************************************************
 *
 * FUNCTION:    SetTimeOfNextAlarm
 *
 * DESCRIPTION: This routine set the time of the next scheduled
 *              alarm. 
 *
 * PARAMETERS:  the time of the next scheduled alarm, or zero if 
 *              no alarm is scheduled.
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	9/1/95	Initial Revision
 *
 ***********************************************************************/
static void SetTimeOfNextAlarm (ULong alarmTime, DWord ref)
{
	UInt cardNo;
	LocalID dbID;
	DmSearchStateType searchInfo;

	DmGetNextDatabaseByTypeCreator (true, &searchInfo, 
		sysFileTApplication, sysFileCDatebook, true, &cardNo, &dbID);

	AlmSetAlarm (cardNo, dbID, ref, alarmTime, true);
}


/***********************************************************************
 *
 * FUNCTION:    DrawAlarm
 *
 * DESCRIPTION: This routine draws the description, time, duration, and 
 *              date of an event.
 *
 * PARAMETERS:  pendingP - record index and alarm time of the event
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	10/14/95	Initial Revision
 *
 ***********************************************************************/
static void DrawAlarm (PendingAlarmType * pendingP)
 {
 	Int							i;
 	Char							chr;
	Char							timeStr [timeStringLength];
	Char							dateStr [dateStringLength];
 	Word							lineCount = 0;
	Word 							duration;
 	Word							length;
 	Word							charsToDraw;
 	Word							maxWidth;
 	Word							dayOfWeek;
	Long 							adjust;
	ULong 						eventTime;
 	SWord							x, y;
 	SWord							extentX, extentY;
	FontID						curFont;
	VoidHand						resH;
	VoidHand						recordH;
	CharPtr						ptr;
	DmOpenRef 					dbP;
	DateTimeType 				dateTime;
	ApptDBRecordType 			apptRec;
	SystemPreferencesType 	sysPrefs;
	

	// Open the appointment database.
	dbP = DmOpenDatabaseByTypeCreator (datebookDBType, sysFileCDatebook, 
		dmModeReadOnly);
	if (!dbP) return;

	ApptGetRecord (dbP, pendingP->recordNum, &apptRec, &recordH);

	curFont = FntSetFont (stdFont);

	// Get the date and time formats.
	PrefGetPreferences (&sysPrefs);


	// Compute the maximum width of a line of the description.
	WinGetWindowExtent (&extentX, &extentY);
	maxWidth = extentX - alarmDescDrawX - alarmDescRightMargin;  
	
	// Draw the event's description.
	ptr = apptRec.description;
	while (true)
		{
		length = FldWordWrap  (ptr, maxWidth);
		if (! length) break;

		charsToDraw = length;
		while (charsToDraw && (ptr[charsToDraw-1] == linefeedChr))
			charsToDraw--;
		WinDrawChars (ptr, charsToDraw, alarmDescDrawX, 
			alarmDescDrawY + (lineCount * FntLineHeight()));
		if (++lineCount >= alarmDescMaxLine) break;
		ptr += length;
		}

	y = alarmDescDrawY + (lineCount * FntLineHeight());

	// Calculate the event's date and time from the alarm time and the alarm
	// advance.  The date and time stored in the record will not be
	// the correct values to display, if the event is repeating.
	adjust = apptRec.alarm->advance;
	switch (apptRec.alarm->advanceUnit)
		{
		case aauMinutes:
			adjust *= minutesInSeconds;
			break;
		case aauHours:
			adjust *= hoursInSeconds;
			break;
		case aauDays:
			adjust *= daysInSeconds;
			break;
		}	
	eventTime = pendingP->alarmTime + adjust;
	
	
	// Display the time of the event if the event has a time.
	if (TimeToInt (apptRec.when->startTime) != apptNoTime)
		{
		// Calculate the duration of the event.
		duration = (apptRec.when->endTime.hours * hoursInMinutes + 
						apptRec.when->endTime.minutes) -
					  (apptRec.when->startTime.hours * hoursInMinutes + 
						apptRec.when->startTime.minutes);


		// Draw the event's time and duration.
		TimSecondsToDateTime (eventTime, &dateTime);
		TimeToAscii (dateTime.hour, dateTime.minute, sysPrefs.timeFormat, timeStr);
	
		x = alarmDescDrawX;
		y += FntLineHeight();
		WinDrawChars (timeStr, StrLen (timeStr), x, y);
		
		x += FntCharsWidth (timeStr, StrLen (timeStr)) + FntCharWidth (spaceChr);
		chr = '-';
		WinDrawChars (&chr, 1, x, y);
		
		TimSecondsToDateTime (eventTime + (duration * minutesInSeconds), &dateTime);
		TimeToAscii (dateTime.hour, dateTime.minute, sysPrefs.timeFormat, timeStr);
		x += FntCharWidth (chr) + FntCharWidth (spaceChr);
		WinDrawChars (timeStr, StrLen (timeStr), x, y);
		}
	
	
	// Draw the name of the day of the week.
	TimSecondsToDateTime (eventTime, &dateTime);

	resH = DmGetResource (strRsc, dayFullNamesStrID);
	ptr = MemHandleLock (resH);
	dayOfWeek = DayOfWeek (dateTime.month, dateTime.day, dateTime.year);
	for (i = 0; i < dayOfWeek; i++)
		ptr = StrChr (ptr, spaceChr) + 1;
	length = (Word) (StrChr (ptr, spaceChr) - ptr);
	
	x = alarmDescDrawX;
	y += FntLineHeight();
	WinDrawChars (ptr, length, x, y);
	MemHandleUnlock (resH);

	x += FntCharsWidth (ptr, length) ;
	chr = commaChr;
	WinDrawChars (&chr, 1, x, y);


	// Draw the event's date.
	x += FntCharWidth (commaChr) + FntCharWidth (spaceChr);
	DateToAscii (dateTime.month, dateTime.day, dateTime.year, 
		sysPrefs.dateFormat, dateStr);
	WinDrawChars (dateStr, StrLen (dateStr), x, y);


	FntSetFont (curFont);

	MemHandleUnlock (recordH);

	DmCloseDatabase (dbP);
 }


/***********************************************************************
 *
 * FUNCTION:    ShowAlarmHandleEvent
 *
 * DESCRIPTION: This routine is the event handler for the alarm dialog
 *              of the Datebook application. 
 *
 * PARAMETERS:  event  - a pointer to an EventType structure
 *
 * RETURNED:    true if the event has handle and should not be passed
 *              to a higher level handler.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	10/10/95	Initial Revision
 *
 ***********************************************************************/
static Boolean ShowAlarmHandleEvent (EventPtr event)
{
	Word index;
	FormPtr frm;
	PendingAlarmType * pendingP;

	// We don't want t allow an other application to be launched 
	// while an alarm is displayed, so we intercept appStop events.
	// All other event are handled by FrmDoDialog.
	if (event->eType == appStopEvent)
		return true;
		
	else if (event->eType == frmUpdateEvent)
		{
		frm = FrmGetActiveForm ();
		FrmDrawForm (frm);
		
		index = FrmGetObjectIndex (frm, AlarmDescGadget);
		pendingP = FrmGetGadgetData (frm, index);
		DrawAlarm (pendingP);
		}

	return false;
}


/***********************************************************************
 *
 * FUNCTION:    AddPendingAlarm
 *
 * DESCRIPTION: This routine add an entry to the pending alarms list.
 *
 * PARAMETERS:  record index
 *              time of the alarm.
 *
 * RETURNED:    true if the alarm  has added to the pending alarms list,
 *              false if the alarm replaced a pending alarm or has not 
 *              added at all.
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	9/20/95	Initial Revision
 *
 ***********************************************************************/
static Boolean AddPendingAlarm (Word recordNum, ULong alarmTime)
{
	Err err;
	Word index;
	Word count;
	Boolean appended;
	VoidHand pendingH;
	PendingAlarmType * pendingP;
	
	// Get the list of pending alarms.
	err = FtrGet (sysFileCDatebook, alarmsFeatureNum, (DWordPtr) &pendingH);
	if (err && (err != ftrErrNoSuchFeature)) return (false);
	
	// If we don't have a list of pending alarms then create one.
	if (err == ftrErrNoSuchFeature)
		{
		pendingH = MemHandleNew (sizeof (PendingAlarmType));
		MemHandleSetOwner (pendingH, 0);
		FtrSet (sysFileCDatebook, alarmsFeatureNum, (DWord) pendingH);
		index = 0;
		appended = true;
		}

	// We have a limit on the number of pending alarms.  The 
	// reasoning for the limit is that if the device is
	// unattended for an extented period of time there many
	// be many alarms pending,  more then you would want to view.
	//
	// If we have a list of pending alarms then add to it. if we're over
	// the limit, drop the oldest alarm from the list.
	else
		{
		count = MemHandleSize (pendingH) / sizeof (PendingAlarmType);
		if (count < apptMaxDisplayableAlarms)
			{		
			MemHandleResize (pendingH, (count + 1) * sizeof (PendingAlarmType));
			index = count;
			appended = true;
			}
		else
			{
			pendingP = MemHandleLock (pendingH);
			MemMove (pendingP, pendingP+1, (count-1) * sizeof (PendingAlarmType));
			MemPtrUnlock (pendingP);
			index = count - 1;			
			appended = false;
			}
		}
		
	// Add the info passed to the pending alarm list.	
	pendingP = MemHandleLock (pendingH);
	pendingP[index].recordNum = recordNum;
	pendingP[index].alarmTime = alarmTime;
	MemPtrUnlock (pendingP);

	return (appended);
}


/***********************************************************************
 *
 * FUNCTION:    PlayAlarmSound
 *
 * DESCRIPTION:	Play a MIDI sound given a unique record ID of the MIDI record in the System
 *						MIDI database.  If the sound is not found, then the default alarm sound will
 *						be played.
 *
 * PARAMETERS:  uniqueRecID	-- unique record ID of the MIDI record in the System
 *										   MIDI database.
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			vmk	8/10/97	Initial version
 *			trev	08/14/97	Ported to dateBook App
 *			vmk	12/11/97	Prevent call to DmFindRecordByID if DmOpenDatabase failed
 *
 ***********************************************************************/
void PlayAlarmSound(ULong uniqueRecID)
{
	Err			err;
	VoidHand		midiH;							// handle of MIDI record
	SndMidiRecHdrType*	midiHdrP;			// pointer to MIDI record header
	BytePtr		midiStreamP;					// pointer to MIDI stream beginning with the 'MThd'
														// SMF header chunk
	UInt			cardNo;							// card number of System MIDI database
	LocalID		dbID;								// Local ID of System MIDI database
	DmOpenRef	dbP = NULL;						// reference to open database
	UInt			recIndex;						// record index of the MIDI record to play
	SndSmfOptionsType	smfOpt;					// SMF play options
	DmSearchStateType	searchState;			// search state for finding the System MIDI database
	Boolean		bError = false;				// set to true if we couldn't find the MIDI record
	
		
	// Find the system MIDI database
	err = DmGetNextDatabaseByTypeCreator(true, &searchState,
			 		sysFileTMidi, sysFileCSystem, false, 
			 		&cardNo, &dbID);
	if ( err )
		bError = true;														// DB not found
	
	// Open the MIDI database in read-only mode
	if ( !bError )
		{
		dbP = DmOpenDatabase (cardNo, dbID, dmModeReadOnly);
		if ( !dbP )
			bError = true;													// couldn't open
		}
	
	// Find the MIDI track record
	if ( !bError )
		{
		err = DmFindRecordByID (dbP, uniqueRecID, &recIndex);
		if ( err )
			bError = true;														// record not found
		}
		
	// Lock the record and play the sound
	if ( !bError )
		{
		// Find the record handle and lock the record
		midiH = DmQueryRecord(dbP, recIndex);
		midiHdrP = MemHandleLock(midiH);
		
		// Get a pointer to the SMF stream
		midiStreamP = (BytePtr)midiHdrP + midiHdrP->bDataOffset;
		
		// Play the sound (ignore the error code)
		// The sound can be interrupted by a key/digitizer event
		smfOpt.dwStartMilliSec = 0;
		smfOpt.dwEndMilliSec = sndSmfPlayAllMilliSec;
		smfOpt.amplitude = (UInt)PrefGetPreference(prefAlarmSoundVolume);
		smfOpt.interruptible = true;
		smfOpt.reserved = 0;
		err = SndPlaySmf (NULL, sndSmfCmdPlay, midiStreamP, &smfOpt, NULL, NULL, false);
		
		// Unlock the record
		MemPtrUnlock (midiHdrP);
		}
	
	// Close the MIDI database
	if ( dbP )
		DmCloseDatabase (dbP);
		
	
	// If there was an error, play the built-in alarm sound
	if ( bError )
		SndPlaySystemSound(sndAlarm);
}


/***********************************************************************
 *
 * FUNCTION:    DisplayAlarm
 *
 * DESCRIPTION: This routine displays all pending alarms.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	8/30/95	Initial Revision
 *
 ***********************************************************************/
void DBDisplayAlarm (void)
{
	Err err;
	Word count = 0;
	DWord	ref;
	ULong alarmTime;
	FormPtr frm;
	FormPtr curForm;
	VoidHand pendingH;
	DmOpenRef dbP;
	PendingAlarmType * pendingP;
	PendingAlarmType pendingInfo;
	
	// Get the list of pending alarms, if we don't have a list of pending 
	// alarms exit.
	err = FtrGet (sysFileCDatebook, alarmsFeatureNum, (DWordPtr) &pendingH);
	if (err) return;


	// Display alarms until there are no more pending
	while (true)
		{	
		count = MemHandleSize (pendingH) / sizeof (PendingAlarmType);
		if (count == 0)
			{
			MemHandleFree (pendingH);
			FtrUnregister (sysFileCDatebook, alarmsFeatureNum);
			break;
			}

		// Get the record number and alarm time, of the next alarm, from 
		// the pending alarms list, and remove the entry for the list.
		pendingP = (PendingAlarmType *) MemHandleLock (pendingH);
		pendingInfo = pendingP[0];
		MemMove (pendingP, pendingP+1, sizeof (PendingAlarmType) * (count-1));
		MemPtrResize (pendingP, sizeof (PendingAlarmType) * (count-1));
		MemHandleUnlock (pendingH);


		frm = FrmInitForm (AlarmDialog);
	
		curForm = FrmGetActiveForm ();
		if (curForm)
			FrmSetActiveForm (frm);
	
		// Set the event handler for the alarm dialog.
		FrmSetEventHandler (frm, ShowAlarmHandleEvent);
	
		// Store the infomation necessary to draw the alarm's description
		// in a gadget object.  This allows us to redraw the 
		// description on a frmUpdate event.
		FrmSetGadgetData (frm, FrmGetObjectIndex (frm, AlarmDescGadget),
			&pendingInfo);

		FrmDrawForm (frm);
		DrawAlarm (&pendingInfo);
		
		// Display the alarm dialog.
		FrmDoDialog (frm);
	
	 	FrmDeleteForm (frm);
	
		FrmSetActiveForm (curForm);

		// Cancel any scheduled repeating alarm sounds and schedure the next
		// alarm
		dbP = DmOpenDatabaseByTypeCreator (datebookDBType, sysFileCDatebook, 
			dmModeReadOnly);
		if (dbP)
			{
			alarmTime = GetTimeOfNextAlarm (&ref);
			if (alarmTime && ref > 0)
				{
				
				alarmTime = ApptGetTimeOfNextAlarm (dbP, alarmTime + minutesInSeconds);
				SetTimeOfNextAlarm (alarmTime, 0);
				}
			DmCloseDatabase (dbP);
			}
		}
}


/***********************************************************************
 *
 * FUNCTION:	AlarmTriggered
 *
 * DESCRIPTION:	This routine is called when the alarm manager informs the 
 *						datebook application that an alarm has triggered.
 *						THIS IS CALLED AT INTERRUPT LEVEL! DONT USE GLOBALS!!
 *
 * PARAMETERS:	time of the alarm.
 *
 * RETURNED:	time of the next alarm
 *
 * REVISION HISTORY:
 *			Name		Date		Description
 *			----		----		-----------
 *			art		9/20/95	Initial Revision
 *			frigino	9/9/97	Switched use of globals to use of prefs
 *									values instead.
 *			vmk		12/9/97	Call DatebookLoadPrefs() to load/fixup our app prefs
 *
 ***********************************************************************/
void AlarmTriggered (SysAlarmTriggeredParamType * cmdPBP)
{
	DatebookPreferenceType	prefs;
	VoidHand		alarmListH;
	WordPtr		alarmListP;
	DmOpenRef	dbP;
	ULong			alarmTime;
	ULong			repeatSoundTime;
	DWord			ref;
	Word			i;
	Word			alarmCount;
	Boolean		quiet;
	Boolean		appended;

	// Open the appointment database.
	dbP = DmOpenDatabaseByTypeCreator (datebookDBType, sysFileCDatebook, 
		dmModeReadOnly);
	if (!dbP)
		return;

	// Read the preferences / saved-state information (will fix up incompatible versions)
	DatebookLoadPrefs (&prefs);

	alarmTime = cmdPBP->alarmSeconds;

	// The reference value contains the number of time the alarm has
	// sounds for an event.
	if (cmdPBP->ref == 0)
		{
		// Get a list of all the appointments that have an alarm scheduled 
		// at the passed time.
		alarmListH =  ApptGetAlarmsList (dbP, alarmTime, &alarmCount, &quiet);
		if (alarmCount != 0)
			{
			// Add the alarms that just trigggered to the pending alarms
			// list.
			alarmListP = (WordPtr) MemHandleLock (alarmListH);
			for (i = 0; i < alarmCount; i++)
				appended = AddPendingAlarm (alarmListP[i], alarmTime);
			// Free alarm data
			MemHandleFree (alarmListH);

			// Play the alarm sound if any the the appointments are timed
			// events and the appointments was appended to the peneding 
			// alarms list.
			if (!quiet && appended)
				{
				// Play the alarm sound.		
				PlayAlarmSound (prefs.alarmSoundUniqueRecID);
				}
			}
		}
	else
		{
		// Pass the following value to the alarm manager, this will be 
		// removed from the alarm table and the display notification will
		// NOT be generated for it.  We don't want display notifications
		// on repeat sounds.
		cmdPBP->purgeAlarm = true;
		// Play the alarm sound.		
		PlayAlarmSound (prefs.alarmSoundUniqueRecID);
		// Play no more
		quiet = false;
		}
	
	// Get the time of the next alarm on any event.
	alarmTime = ApptGetTimeOfNextAlarm (dbP, alarmTime + minutesInSeconds);
	ref = 0;

	// If the time of the next event's alarm is after the time of the next 
	// repeat  sound, schedule an alarm for the repeat sound.
	if ((!quiet) && cmdPBP->ref < prefs.alarmSoundRepeatCount)
		{
		repeatSoundTime = cmdPBP->alarmSeconds + prefs.alarmSoundRepeatInterval;

		if (((alarmTime == 0) || (repeatSoundTime < alarmTime)) && 
			 (repeatSoundTime >= TimGetSeconds ()))
			{
			alarmTime = repeatSoundTime;
			ref = cmdPBP->ref + 1;
			}
		}

	SetTimeOfNextAlarm (alarmTime, ref);				

	DmCloseDatabase (dbP);
}


/***********************************************************************
 *
 * FUNCTION:    RescheduleAlarms
 *
 * DESCRIPTION: This routine computes the time of the next alarm and 
 *              compares it to the time of the alarm scheduled with
 *              Alarm Manager,  if they are different it reschedules
 *              the next alarm with the Alarm Manager.
 *
 * PARAMETERS:  dbP - the appointment database
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	9/5/95	Initial Revision
 *
 ***********************************************************************/
void RescheduleAlarms (DmOpenRef dbP)
{
	DWord ref;
	ULong timeInSeconds;
	ULong nextAlarmTime;
	ULong scheduledAlarmTime;

	scheduledAlarmTime = GetTimeOfNextAlarm (&ref);
	timeInSeconds = TimGetSeconds ();
	if ((timeInSeconds < scheduledAlarmTime) ||
	    (scheduledAlarmTime == 0) ||
	    (ref > 0))
		scheduledAlarmTime = timeInSeconds;
	
	nextAlarmTime = ApptGetTimeOfNextAlarm (dbP, scheduledAlarmTime);

	// If the scheduled time of the next alarm is not equal to the
	// calculate time of the next alarm,  reschedule the alarm with 
	// the alarm manager.
	if (scheduledAlarmTime != nextAlarmTime)
		{
		SetTimeOfNextAlarm (nextAlarmTime, 0);
		}	
}


/***********************************************************************
 *
 * FUNCTION:    AlarmReset
 *
 * DESCRIPTION: This routine is called when the system time is changed
 *              by the Preference application, or when the device is reset.
 *                
 * PARAMETERS:  newerOnly - If true, we will not reset the alarm if the 
 *              time of the next (as calculated) is greater then the 
 *              currently scheduled alarm.
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	9/21/95	Initial Revision
 *       art	11/18.96	Reseting time will nolong trigger alarms.
 *
 ***********************************************************************/
void AlarmReset (Boolean newerOnly)
{
	DWord ref;
	ULong currentTime;
	ULong alarmTime;
	DmOpenRef dbP;
		
	if (newerOnly)
		{
		alarmTime = GetTimeOfNextAlarm (&ref);
		currentTime = TimGetSeconds ();
		if ( alarmTime && (alarmTime <= currentTime))
			return;
		}

	// Clear any pending alarms.
	SetTimeOfNextAlarm (0, 0);

	// Open the appointment database.
	dbP = DmOpenDatabaseByTypeCreator (datebookDBType, sysFileCDatebook, 
		dmModeReadOnly);
	if (!dbP) return;

	RescheduleAlarms (dbP);

	DmCloseDatabase (dbP);
}


/***********************************************************************
 *
 * FUNCTION:    DisplayAlarm
 *
 * DESCRIPTION: This is a branch island for the DisplayAlarm function.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			scl	1/28/98	Initial Revision
 *
 ***********************************************************************/
// Note: We need to create a branch island to DBDisplayAlarm in order to successfully
//  link this application for the device.
void DisplayAlarm(void)
{
	DBDisplayAlarm();
}
