/*
================================ 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        :   aplaunch.c
Author(s)   :   Henry Fok
Company     :   VTech Informations Ltd.
Project     :   Helio 
Date:	    :   October 1st, 1999
Purpose:	:   application c file
Revision    :   1.1
Note        :   None
===========================================================================
*/              



#include "app.h"
#include "appfunc.h"

extern BOOLEAN draw_view_edit_scrollbar;

/********************************************************
* Function:	PhonebookAppLaunch
* Purpose: 	This function is called to launch the 
phonebook application
* Scope:		application/internal
* Input:		None
* Output:		None
* Return:		TRUE if handled
FALSE if not handled
* Comment: 	None
*********************************************************/
BOOLEAN PhonebookAppLaunch(WORD cmd, void *cmd_ptr)
{
	
	UWORD 			num_rec, count;
	UWORD 			byte_read;
	USHORT 			field_num, total_entry, entry_count = 0;
	RecordID 		rec_id;
    BYTE            *buffer;
	BYTE 			*prepare_string;
    DmFieldArray    dm_field_array;
    DmFieldBuffer   *dm_field_buffer;
	
	if (cmd == LAUNCH_CMD_GOTO_REC && DataRecordInfo(((GotoRec*)cmd_ptr)->dbid, ((GotoRec*)cmd_ptr)->rec_id, NULL, NULL, NULL, NULL, NULL) != TRUE)
	{
		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:
		UIApplicationInit();
		PhonebookAppRestore(FALSE);
		EventLoop();	
		if (entry_low_memory == FALSE || (entry_low_memory == TRUE && entry_old_edit == FALSE))
			PhonebookAppSave();
		UIDeleteAllAppObjects();
		DataCloseDB(pb_dbid);
		return TRUE;
	case LAUNCH_CMD_FIND:
		PhonebookDatabaseChecking();
		app_id = SysGetActiveAppID();		
		DataTotalRecord(pb_dbid, &num_rec);
		count = 0;
		while (count < num_rec)
		{
			DataOpenRecord(pb_dbid, count, &rec_id, NULL);
			DataGetAllField(pb_dbid, rec_id, &dm_field_array);
			total_entry = dm_field_array.total_entry;																			
			dm_field_buffer = dm_field_array.data_array;
			entry_count = 0;
			while (entry_count < total_entry)
			{	
				//do not search non-text data
				if((entry_count!=26)&&(entry_count!=27)&&(entry_count!=28))
				{
					if (GlobalFindSearchText((BYTE*)cmd_ptr, (BYTE*)(dm_field_buffer[entry_count]).data) >= 0)
					{
						PhonebookPrepareFindText(pb_dbid, rec_id, &prepare_string);
						GlobalFindAddItem(app_id, pb_dbid, rec_id, entry_count, prepare_string, FALSE);
						pfree(prepare_string);
						break;
					}
				}
				entry_count ++;
			}
			DataFreeFieldArray(dm_field_array);        
			count ++;
		}
		return TRUE;			
	case LAUNCH_CMD_GOTO_REC:
		gf_entry = TRUE;
		PhonebookDatabaseChecking();
		PhonebookGotoItem(((GotoRec*)cmd_ptr)->dbid, ((GotoRec*)cmd_ptr)->rec_id, ((GotoRec*)cmd_ptr)->field_num, ((GotoRec*)cmd_ptr)->find_string);
		if (((GotoRec*)cmd_ptr)->find_string != NULL)
			pfree(((GotoRec*)cmd_ptr)->find_string);
		
		pfree(cmd_ptr);
		
		EventLoop();	
		
		if ((entry_low_memory == FALSE || (entry_low_memory == TRUE && entry_old_edit == FALSE)) 
			&& (gf_entry == FALSE || (gf_entry == TRUE && entry_old_edit == FALSE)))
			PhonebookAppSave();
		
		UIDeleteAllAppObjects();
		DataCloseDB(pb_dbid);
		return TRUE;
	case LAUNCH_CMD_ALARM_HIT:
		pfree(cmd_ptr);
		DataCloseDB(pb_dbid);
		return TRUE;
	default:
		return FALSE;
	}
	return FALSE;
}

/********************************************************
* Function:	PhonebookPrepareFindText
* 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 PhonebookPrepareFindText(DatabaseID dbid, RecordID rec_id, BYTE **prepare_string)
{
	SHORT			string_name_width, string_phone_width;
	ObjectBounds	name_bounds, phone_num_bounds;
	BYTE			*name, *phone_num, *buffer;
	UWORD			byte_read, name_num_chars;
	
	name_bounds.xcoord	= 0;
	name_bounds.ycoord	= 0;
	name_bounds.width	= 67;
	name_bounds.height	= 9;
	
	phone_num_bounds.xcoord	= 0;
	phone_num_bounds.ycoord	= 0;
	phone_num_bounds.width	= 67;
	phone_num_bounds.height	= 9;
	
	*prepare_string = (BYTE*)pmalloc(100*sizeof(BYTE));
	DataGetField(dbid, rec_id, 2, &buffer, &byte_read);
	name = (BYTE*)pmalloc((strlen(buffer) + 10) *sizeof(BYTE));
	strcpy(name, buffer);
	qfree(buffer);
	StrChopString(&name_bounds, name, SMALL_FONT, TRUE, 0);
	string_name_width = StrGetWidth(name, SMALL_FONT);
	DataGetField(dbid, rec_id, 5, &buffer, &byte_read);
	phone_num = (BYTE*)pmalloc((strlen(buffer) + 10) *sizeof(BYTE));
	strcpy(phone_num, buffer);
	qfree(buffer);
	StrChopString(&phone_num_bounds, phone_num, SMALL_FONT, TRUE, 0);
	string_phone_width = StrGetWidth(phone_num, SMALL_FONT);
	strcpy(*prepare_string, name);
	name_num_chars = strlen(name);
	(*prepare_string)[name_num_chars] = 11;
	(*prepare_string)[name_num_chars + 1] = 139 - string_phone_width - string_name_width;
	sprintf((char*)(*prepare_string + name_num_chars + 2), "%s", phone_num);
	pfree(name);
	pfree(phone_num);
}

/********************************************************
* Function:	PhonebookGotoItem
* 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 PhonebookGotoItem(DatabaseID dbid, RecordID rec_id, USHORT field_num, BYTE *search_string)
{
    BYTE *buffer, out_string[200], object_type;
	UWORD byte_read, rec_num;
	WORD count, total_num_lines;
	USHORT item_num, temp_top_row_num = 0;
	UBYTE cat;
	WORD highlight_char_pos = 0, num_lines = 0, line_num;
	Field *field_ptr;
	BOOLEAN found = FALSE;
	EvtType temp_event;
    Scrollbar *scroll_ptr;
	Textbox *textbox_ptr;
	BOOLEAN	highlight = FALSE;
	SHORT	row_num_array[30];
	BYTE application_status;
	
	
	/* global variables initialisation */
	pb_dbid = dbid;
    pressed_object = 0;
    current_cate = NULL;
    char_start = PBCHARA;
    temp_cate = NULL;
    save_cate = NULL;
    save_first_letter = PBCHARA;
    table_font_size = SMALL_FONT;
    SetStatus(TEL_LIST,FALSE,FALSE,0,FALSE);
    list_tel_list.list_id = LIST_NAME;
    list_find.list_id = LIST_FIND_RESULT_NAME;
    list_tel_list.dbid = list_find.dbid = 0;
    list_tel_list.max_num_items_display = list_find.max_num_items_display = 0;
    list_tel_list.num_items_display = list_find.num_items_display = 0;
    list_tel_list.total_num_items = list_find.total_num_items = 0;
    list_tel_list.top_item_num = list_find.top_item_num = 0;        
    list_tel_list.record_id_block = list_find.record_id_block = NULL;        
	list_tel_list.dbid = list_find.dbid = pb_dbid;
	
	FormInitAllFormObjects(FORM_TEL_LIST);
	FormInitAllFormObjects(FORM_VIEW_EDIT);
	
	
    if (MemoryLow)
        entry_low_memory = TRUE;
    else 
		entry_low_memory = FALSE;
    
	DataGetField(pb_dbid, PB_STATUS, 0, &buffer, &byte_read);
	
	application_status = *buffer;
    
	entry_old_edit = (application_status != TEL_LIST)&&(application_status != -1);
    qfree(buffer);    
	
	/* Allocate global variable */
	field_buffers = (BYTE**)qmalloc(27*sizeof(BYTE*));
	for (count = 0; count <27; count++)
		field_buffers[count] = NULL;
	current_cate = (BYTE*)qmalloc(30*sizeof(BYTE));
	
	DataRecIDtoNum(dbid, rec_id, &rec_num);
	DataOpenRecord(dbid, rec_num, &rec_id, NULL);
	DataRecordInfo(dbid, rec_id, NULL, &cat, NULL, NULL, NULL);
	//set up current cate
	DataCategoryName(dbid, cat, current_cate);
	//set up char start
	DataGetField(dbid, rec_id, 2, &buffer, &byte_read);
	char_start = buffer[0];
	qfree(buffer);
	
    DataGetField(pb_dbid, PB_STATUS, 2, &buffer, &byte_read);
    strcpy(find_string, buffer);
    qfree(buffer);
	
	
    DataGetField(pb_dbid, PB_STATUS, 3, &buffer, &byte_read);
    font_size = *buffer;
    qfree(buffer);
	
	//set up FORM_TEL_LIST
    draw_scrollbar = FALSE;
	PhonebookRecordToList(pb_dbid, current_cate, char_start, NULL);
    draw_scrollbar = TRUE;
	PhonebookCateNameToPopupTrigger(pb_dbid);
	if (ControlPopupFindItemNum(POPUP_TRIGGER_CATE, current_cate, &item_num) == TRUE) 
		ControlPopupSetSelectedItem(POPUP_TRIGGER_CATE, (SHORT)item_num);
	else
		ControlPopupSetSelectedItem(POPUP_TRIGGER_CATE, 0);
	DataOpenRecord(dbid, rec_num, &rec_id, NULL);
	
	//set up FORM_VIEW_EDIT
	/* field_buffers */
	for (count = 0; count < 27; count++)
	{
		DataGetField(pb_dbid, rec_id, (USHORT)count, &buffer, &byte_read);			
		field_buffers[count] = (BYTE*)qmalloc((strlen(buffer) + 1)*sizeof(BYTE));
		strcpy(field_buffers[count], buffer);
		qfree(buffer);
	}
	// temp_cate
	temp_cate = (BYTE*)qmalloc(30*sizeof(BYTE));
	strcpy(temp_cate, current_cate);
	
	/* app_status */
	if (field_num == 25)
		app_status.status = NOTES_VIEW;
	else app_status.status = VIEW;						
	app_status.rec_id = rec_id;
	app_status.new_record = FALSE;
	app_status.company = FALSE;
	app_status.home = FALSE;
	
	PhonebookPrepareFirstLastName(field_buffers[0], field_buffers[1], out_string);
	StringSetText(STRING_VIEW_EDIT_LARGE_TITLE,		field_buffers[4]);
	StringSetText(STRING_VIEW_EDIT_LARGE_COMPANY,	field_buffers[3]);
	
	app_status.home = TRUE;
	
	/* Setup FORM_VIEW_EDIT */
	
	PhonebookRecordToFieldBuffers(app_status.rec_id);
	PhonebookFieldBuffersToField();
	PhonebookViewEditSetupScreen();
	PhonebookGetMappedRowNum(row_num_array);
	PhonebookCateNameToPopupTrigger(pb_dbid);
	ControlPopupDeleteItem(POPUP_TRIGGER_CATE, 0);
	if (ControlPopupFindItemNum(POPUP_TRIGGER_CATE, temp_cate, &item_num) == TRUE) 
		ControlPopupSetSelectedItem(POPUP_TRIGGER_CATE, (SHORT)item_num);
	else
		ControlPopupSetSelectedItem(POPUP_TRIGGER_CATE, 0);	
	if (save_cate != NULL)
		qfree(save_cate);
	save_cate = (BYTE*)qmalloc(30*sizeof(BYTE));
	strcpy (save_cate, temp_cate);
	highlight = FALSE;
	PhonebookSetViewEditTable(FORM_VIEW_EDIT, TABLE_VIEW_EDIT);
    draw_view_edit_scrollbar = FALSE;
	PhonebookViewEditTableSetScrollbar(TABLE_VIEW_EDIT, SCROLLBAR_VIEW_EDIT);
    draw_view_edit_scrollbar = TRUE;
	
	if (highlight == FALSE)
	{
		PhonebookChangeFontSize(FORM_VIEW_EDIT, font_size);		
		if(field_num==25)
			FormPopupForm(FORM_NOTES);
		else
			FormPopupForm(FORM_VIEW_EDIT);
		return;
	}
}

/********************************************************
* Function:	PhonebookGetMappedRowNum
* Purpose: 	This function is called to mapped row_num				
* Scope:		application/internal
* Input:		None
* Output:		USHORT array
* Return:		None
* Comment: 	None
*********************************************************/
void PhonebookGetMappedRowNum(SHORT *array)
{
	SHORT		row_count, row_up_to;
	
	array[0]	= -1;
	array[1]	= -1;
	array[2]	= -1;
	array[3]	= -1;
	array[4]	= -1;	
	
	row_up_to = 0;
	for (row_count = 5; row_count < 10; row_count++)
	{
		if (strlen(field_buffers[row_count]))
		{
			array[row_count] = row_up_to;
			row_up_to ++;
		}
		else array[row_count] = -1;
	}	
	
	if (strlen(field_buffers[10]) || strlen(field_buffers[11]) ||
		strlen(field_buffers[12]) || strlen(field_buffers[13]) ||
		strlen(field_buffers[14]))	
		array[10] = array[11] = array[12] = array[13] = array[14] = row_up_to;
	else array[10] = array[11] = array[12] = array[13] = array[14] = -1;
	
	
	row_up_to = 0;
	for (row_count = 15; row_count < 17; row_count++)
	{
		if (strlen(field_buffers[row_count]))
		{
			array[row_count] = row_up_to;
			row_up_to ++;
		}
		else array[row_count] = -1;
	}	
	
	if (strlen(field_buffers[17]) || strlen(field_buffers[18]) ||
		strlen(field_buffers[19]) || strlen(field_buffers[20]) ||
		strlen(field_buffers[21]))	
	{
		array[17] = array[18] = array[19] = array[20] = array[21] = row_up_to;
		row_up_to ++;
	}
	else array[17] = array[18] = array[19] = array[20] = array[21] = -1;
	
	for (row_count = 22; row_count < 26; row_count++)
	{
		if (strlen(field_buffers[row_count]))
		{
			array[row_count] = row_up_to;
			row_up_to ++;
		}
		else array[row_count] = -1;
	}	
}
