/*
================================ COPYRIGHT ================================
The contents of this file are subject to the VTech Informations Ltd. License
of VT-OS Ver. 1.1 operating system (the "License"); you may not use this 
file except in compliance with the License.  

Software distributed under the License is distributed on an "AS IS" basis, 
WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License 
for the specific language governing rights and limitations under the License.
  
The Original Code is VT-OS Ver. 1.1 Operating System, released 
on October 1st, 1999
	
The Initial Developer of the Original Code is VTech Informations Ltd.  All 
codes are Copyright (C) VTech Informations Ltd. 1999.  All Rights Reserved.
===========================================================================
*/

/*
===========================================================================
File        :   annlch.c
Author(s)   :   David Lo
Company     :   VTech Informations Ltd.
Project     :   Helio 
Date:	    :   October 1st, 1999
Purpose:	:   application c file
Revision    :   1.1
Note        :   None
===========================================================================
*/              


#include "stdafx.h"
#include "Ann.h"
#include "AnnFunc.h"
#include "AnnDB.h"
#include "AnnLch.h"
///#define	DEBUG  

/*****************************************************************
********************** Global Variables **************************
*****************************************************************/

/********************************************************
* Function:	ToDoAppLaunch
* Purpose: 	This function is called to launch the 
*			To DO List application
* Scope:	application/internal
* Input:	None
* Output:	None
* Return:	TRUE if handled
*			FALSE if not handled
* Comment: 	None
*********************************************************/
BOOLEAN AnnAppLaunch(WORD cmd, void *cmd_ptr)
{
#ifdef	PR31700
	UWORD		num_rec, count, byte_read;
	USHORT		field_num;
	BYTE		*buffer, *prepare_string;
#endif
	RecordID	rec_id;
	AlarmEvent alarm_evt;
	RTM hit_time;
	AppID		app_id;
	
#ifdef	DEBUG
	printf("\n*** Anniversaries Lanuch Start ***\n");
#endif
	/* Temp Alarm Use */
	DataFindDB(ANNDB, &ann_dbid);
	/* Temp Alarm Use */
	///	if (cmd == LAUNCH_CMD_GOTO_REC && DataRecordInfo(((GotoRec*)cmd_ptr)->dbid, ((GotoRec*)cmd_ptr)->rec_id, NULL, NULL, NULL, NULL, NULL) != TRUE)
	if (cmd == LAUNCH_CMD_GOTO_REC && DataRecordInfo(ann_dbid, ((GotoRec*)cmd_ptr)->rec_id, NULL, NULL, NULL, NULL, NULL) != TRUE)
	{
#ifdef	DEBUG
        printf("\n*** Anniversaries Lanuch 1 ***\n");
#endif
		if (((GotoRec*)cmd_ptr)->find_string != NULL)
			pfree(((GotoRec*)cmd_ptr)->find_string);
		pfree(cmd_ptr);
		
		cmd = LAUNCH_CMD_NORMAL_LAUNCH;
	}		
	
	switch(cmd)
	{
	case	LAUNCH_CMD_NORMAL_LAUNCH:
#ifdef	DEBUG
        printf("\n*** Anniversaries Lanuch 2 ***\n");
#endif
		UIApplicationInit();
		AnnAppRestore(FALSE);
		EventLoop();
		/* Exit Normal Launch */
#ifdef PR31700
		if (entry_low_memory == FALSE || entry_old_edit == FALSE)
			AnnAppSave();
#endif
#ifdef PC_SIM
		///				rec_id = 1099;
		///				DataWriteField(ann_dbid, ANN_EDIT_INFO, 0, 4, (BYTE*)&rec_id);
		AnnAppSave();
		AnnAppRestore(FALSE);
		EventLoop();
#endif
		UIDeleteAllAppObjects();
		
		if (cmd_ptr != NULL)
			pfree(cmd_ptr);
		return TRUE;
		
	case	LAUNCH_CMD_FIND:
#ifdef 	PR31700
#ifdef	DEBUG
        printf("\n*** Anniversaries Lanuch 3 ***\n");
#endif
		app_id = SysGetActiveAppID();
		AnnDatabaseChecking();
		DataTotalRecord(ann_dbid, &num_rec);
		
		for (count =0; count <num_rec; count++)
		{
			DataOpenRecord(ann_dbid, count, &rec_id, NULL);
			
			for (field_num =1; field_num <2; field_num++)
			{
				DataGetField(ann_dbid, rec_id, field_num, &buffer, &byte_read);
				
				if (GlobalFindSearchText((BYTE*)cmd_ptr, buffer) >= 0)
				{
					AnnPrepareFindText(ann_dbid, rec_id, &prepare_string);
					GlobalFindAddItem(app_id, ann_dbid, rec_id, field_num, prepare_string, FALSE);
					pfree(prepare_string);
					qfree(buffer);
					break;
				}
				qfree(buffer);
			}
			DataCloseRecord(ann_dbid, rec_id);
		}
		if (cmd_ptr != NULL)
			pfree(cmd_ptr);
#endif
		return TRUE;
		
	case	LAUNCH_CMD_GOTO_REC:
#ifdef PR31700
#ifdef	DEBUG
        printf("\n*** Anniversaries Lanuch 4 ***\n");
#endif
		AnnDatabaseChecking();
		AnnGotoItem(((GotoRec*)cmd_ptr)->dbid, ((GotoRec*)cmd_ptr)->rec_id,
			((GotoRec*)cmd_ptr)->field_num, ((GotoRec*)cmd_ptr)->find_string);
		
		/* Check Goto from Find or Other Application */
		if (cmd_ptr != NULL)
		{
			if (((GotoRec*)cmd_ptr)->find_string != NULL)
				pfree(((GotoRec*)cmd_ptr)->find_string);
			pfree(cmd_ptr);
		}
		EventLoop();
		/* Exit Goto Record */
#ifdef PR31700
		if (entry_low_memory == FALSE || entry_old_edit == FALSE)
			AnnAppSave();
#endif
		UIDeleteAllAppObjects();
#endif
     			return TRUE;
				
	case	LAUNCH_CMD_ALARM_HIT:
#ifdef	DEBUG
        printf("\n*** Anniversaries Lanuch 5 ***\n");
#endif
		
#ifdef PC_SIM
		UIApplicationInit();
		
		if (DataFindDB(ANNDB, &ann_dbid) != TRUE)
		{
			AnnDatabaseInit();
			AnnAppRestore(TRUE);
		}
		else
			AnnAppRestore(FALSE);
		/* Exit Normal Launch */
		AnnAppSave();
		UIDeleteAllAppObjects();
		AnnSetAllRecordsAlarm(0);
#endif
#ifdef 	PR31700
		AnnDatabaseChecking();
		rec_id = ((AlarmEventHit *) cmd_ptr)->rec_id;
#ifdef	DEBUG
		printf("\n*** Set Next Alarm ID = %d ***", rec_id);
#endif
#else
		rec_id = 1004;
#endif
		AnnSetNextRecordAlarm(rec_id);
		
		if (cmd_ptr != NULL)
			pfree(cmd_ptr);
		return TRUE;
	default:
		return FALSE;
	}
	return FALSE;
}

/********************************************************
* Function:	ToDoPrepareFindText
* Purpose: 	This function is called to prepare the text 
*			for a record to be displayed in the global find 
*			application
* Scope:	application/internal
* Input:	dbid
*			rec_id
*			prepare_string
* Output:	None
* Return:	None
* Comment: 	None
*********************************************************/
void AnnPrepareFindText(DatabaseID dbid, RecordID rec_id, BYTE **prepare_string)
{
	SHORT			string_content_width, string_anndate_width;
	ObjectBounds	content_bounds, anndate_bounds;
	BYTE			*content, *anndate, *buffer;
	UWORD			byte_read, name_num_chars;
	
	
	
	content_bounds.xcoord	=0;
	content_bounds.ycoord	=0;
	content_bounds.width	=67;
	content_bounds.height	=9;
	
	anndate_bounds.xcoord	=0;
	anndate_bounds.ycoord	=0;
	anndate_bounds.width	=60;
	anndate_bounds.height	=9;
	
	*prepare_string = (BYTE*)pmalloc(100*sizeof(BYTE));
	/* Get Anniver Content */
	DataGetField(dbid, rec_id, 1, &buffer, &byte_read);
    content = (BYTE*)pmalloc((strlen(buffer) + 10) *sizeof(BYTE));
	strcpy(content, buffer);
    qfree(buffer);
	StrChopString(&content_bounds, content, SMALL_FONT, TRUE, 0);
	string_content_width = StrGetWidth(content, SMALL_FONT);
	/* Get Anniver Date */
	DataGetField(dbid, rec_id, 2, &buffer, &byte_read);
    anndate = (BYTE*)pmalloc((strlen(buffer) + 10) *sizeof(BYTE));
	strcpy(anndate, buffer);
	qfree(buffer);
	StrChopString(&anndate_bounds, anndate, SMALL_FONT, TRUE, 0);
	string_anndate_width = StrGetWidth(anndate, SMALL_FONT);
	
	strcpy(*prepare_string, content);
	name_num_chars = strlen(content);
	
	(*prepare_string)[name_num_chars] = 11;
	(*prepare_string)[name_num_chars + 1] = 139 - string_content_width - string_anndate_width;
	sprintf((char*)(*prepare_string + name_num_chars + 2), "%s", anndate);
	pfree(content);
	pfree(anndate);
}

/********************************************************
* Function:	ToDoGotoItem
* Purpose: 	This function is called to init all related variables
*			and goto the specific form to display the required record
* Scope:	application/internal
* Input:	dbid
*			rec_id
*			field_num
*			search_string
* Output:	None
* Return:	None
* Comment: 	None
*********************************************************/
void AnnGotoItem(DatabaseID dbid, RecordID rec_id, USHORT field_num, BYTE *search_string)
{
	BYTE		object_type, *buffer;
	Field		*fld_addr;
	WORD		total_num_lines;
	WORD		highlight_char_pos =0, line_num;
	UWORD		byte_read, rec_num;
	BOOLEAN		found =FALSE;
	RTM			time;
	
	/* Set up app_status variables */
	app_status.rec_id = rec_id;
	/* Allocate global variable */
	if(ann_field_buffer != NULL)
		qfree(ann_field_buffer);
	ann_field_buffer = (BYTE**)qmalloc(1*sizeof(BYTE*));
	ann_field_buffer[0] = NULL;
	/* Set up app_status variables */
	AnnRecordToVariable();
	/* Set up the Global variable */
	pressed_object1 = FALSE;
	pressed_object2 = FALSE;
	select_goto = FALSE;
	pen_down = FALSE;
	view_records = FALSE;
	/* Set up selected year, month, day */
	RtcGetTime(&time);
	
#ifdef PC_SIM	/* Testing */
	time.year = 1998;
	time.mon = 1;
	time.mday = 4;
#endif			/* Testing */
	
	app_status.selected_year = time.year;
	app_status.selected_month = time.mon;
	app_status.selected_day = time.mday;
	
	AnnDatabaseChecking();
	
	/* Initialisation all the Forms */
	FormInitAllFormObjects(FORM_ANN_LIST);
	FormInitAllFormObjects(FORM_ANN_VIEWING);
	FormInitAllFormObjects(FORM_ANN_NEW);
	FormInitAllFormObjects(FORM_ANN_WEEK_SETTINGS);
	FormInitAllFormObjects(FORM_ALARM_SETTINGS);
	FormInitAllFormObjects(FORM_ANN_DATE_SETTINGS);
	FormInitAllFormObjects(FORM_YEARLY_SETTINGS);
	FormInitAllFormObjects(FORM_SAVE_CHANGES);
	FormInitAllFormObjects(FORM_ITEM_ERASE);	
	FormInitAllFormObjects(FORM_INVALID_INPUT);
	
	DataGetField(ann_dbid, ANN_EDIT_INFO, 32, &buffer, &byte_read);
	table_font = (BYTE)(*buffer);
	qfree(buffer);
	
	field_top_line = 0;
	field_insert_pt_pos = 0;
	AnnViewingSetUpScreen();
	FormGetObjectPointer(FIELD_ANN_VIEWING, &object_type, (void **)&fld_addr);
	
	/* Goto to select text */
	if (search_string != NULL)
	{
		DataRecIDtoNum(ann_dbid, rec_id, &rec_num);
		DataOpenRecord(ann_dbid, rec_num, &rec_id, NULL);
		DataGetField(ann_dbid, rec_id, 1, &buffer, &byte_read);
		strcpy(ann_field_buffer[0], buffer);
		qfree(buffer);
		
		highlight_char_pos = GlobalFindSearchText(search_string, ann_field_buffer[0]);
		total_num_lines = fld_addr->field_total_num_lines;
		
		for (line_num =0; line_num <total_num_lines; line_num++)
		{
			if ((highlight_char_pos >= fld_addr->field_lineinfo[line_num].start) &&
				(highlight_char_pos <= (fld_addr->field_lineinfo[line_num].start +
				fld_addr->field_lineinfo[line_num].length -1)))
			{
				found = TRUE;
				
				if (line_num > (total_num_lines - fld_addr->field_num_lines_displayed))
					line_num = (total_num_lines - fld_addr->field_num_lines_displayed);
				fld_addr->field_top_line_num = line_num;
				break;
			}
		}
		
		if (!found)
			fld_addr->field_top_line_num = 0;
		
		field_top_line = fld_addr->field_top_line_num;
		AnnSetUpFieldScreen(FORM_ANN_VIEWING);
		AnnFieldSetScrollbar(FIELD_ANN_VIEWING, SCROLLBAR_ANN_VIEWING);
		
		fld_addr->field_highlight_start_char = highlight_char_pos;
		fld_addr->field_highlight_end_char = highlight_char_pos + strlen(search_string) - 1;
		fld_addr->field_highlight_length = strlen(search_string);
		fld_addr->field_attr.field_highlight = TRUE;
		FormSetFormActiveObject(FORM_ANN_VIEWING, fld_addr->identification.ui_object_id);
	}
	/* Disable the field object */
	show_line = FALSE;
	goto_highlight = TRUE;
	FormPopupForm(FORM_ANN_VIEWING);
}

/*****************************************************************
* Function:	AnnLaunchApplication
* Purpose: 	This function is used to launch to other application
*		depend on the selection
* Scope:	application
* Input:	None
* Output:	None
* Return:	None
* Comment: 	None
*****************************************************************/
#ifdef PR31700
void AnnLaunchApplication()
{
	SHORT	popup_item_num;
	AppID   appid;
	BYTE	*launchtosch;
	
	ControlPopupGetSelectedItem(POPUP_TRIGGER_CATEGORIES, &popup_item_num);
	
	if (popup_item_num == 0)
	{
		SysGetAppID(TODO, &appid);
		EvtAppendEvt(EVT_APP_STOP, 0, 0, 0, NULL);
		EvtAppendEvt(EVT_APP_LAUNCH, appid, LAUNCH_CMD_NORMAL_LAUNCH, 0, NULL);
	}
	else if (popup_item_num != 4)
	{
		SysGetAppID(SCHEDULER, &appid);
		EvtAppendEvt(EVT_APP_STOP, 0, 0, 0, NULL);
		
		launchtosch = (BYTE*)pmalloc(1*sizeof(BYTE));
		
		switch(popup_item_num)
		{
		case 1:	*launchtosch = 0;
			break;
			
		case 2:	*launchtosch = 1;
			break;
			
		case 3:	*launchtosch = 2;
			break;
		}
		EvtAppendEvt(EVT_APP_LAUNCH, appid, LAUNCH_CMD_NORMAL_LAUNCH, 0, launchtosch);
	}
}
#endif
