/*
================================ 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        :   appsave.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 "stdafx.h"
#include "app.h"
#include "appfunc.h"

//#define DEBUG_NUM
//#define DEBUG_MICH

#define WITHSOUND

/********************************************************
* Function:	SchedulerDatabaseChecking
* Purpose: 	This function is called to check whether the required database 
is already exist or not. If not, it will create it
* Scope:		application/internal
* Input:		None
* Output:		None
* Return:		None
* Comment: 	None
*********************************************************/
void SchedulerDatabaseChecking()
{
	BYTE	application_status;
	BYTE	font_size = SMALL_FONT;
	UWORD	count = 1000;
	
	if (DataFindDB(SCHAPPDB, &sch_appmt_dbid) != TRUE)
	{
		/* New Database of appointment */
		DataNewDB(SCHAPPDB,1,SCHAPP,&sch_appmt_dbid);
		DataOpenDB(sch_appmt_dbid, 0, OPEN_RW);
	}
	else if (DataIsDBOpen(sch_appmt_dbid, NULL, NULL) == FALSE)
        DataOpenDB(sch_appmt_dbid, 0, OPEN_RW);
	
	
	if (DataFindDB(SCHVOICEDB, &sch_voice_dbid) != TRUE)
	{
		/* New Database of voice */
		DataNewDB(SCHVOICEDB,1,SCHAPP,&sch_voice_dbid);
        DataOpenDB(sch_voice_dbid, DB_NO_SORT, OPEN_RW);
	}
	else if (DataIsDBOpen(sch_voice_dbid, NULL, NULL) == FALSE)
        DataOpenDB(sch_voice_dbid, DB_NO_SORT, OPEN_RW);
	
	// Michelle add 071299
	if (DataFindDB(SCHREPDB, &sch_repeat_dbid) != TRUE)
	{
		/* New Database of repeat */
		DataNewDB(SCHREPDB,1,SCHAPP,&sch_repeat_dbid);
        DataOpenDB(sch_repeat_dbid, F_REPEAT_NUM, OPEN_RW);
	}
	else if (DataIsDBOpen(sch_repeat_dbid, NULL, NULL) == FALSE)
        DataOpenDB(sch_repeat_dbid, F_REPEAT_NUM, OPEN_RW);
	// end add 071299
	
	//Michelle add 171299
	if (DataFindDB(SCHEXPDB, &sch_except_dbid) != TRUE)
	{
		/*New Database of repeat exception */
		DataNewDB(SCHEXPDB, 1, SCHAPP, &sch_except_dbid);
		DataOpenDB(sch_except_dbid, F_REPEAT_NUM, OPEN_RW);
	}
	else if (DataIsDBOpen(sch_except_dbid, NULL, NULL) == FALSE)
		DataOpenDB(sch_except_dbid, F_REPEAT_NUM, OPEN_RW);
	// end add 171299
	
	if (DataRecordInfo(sch_appmt_dbid, SCH_STATUS, NULL, NULL, NULL, NULL, NULL) != TRUE)
	{
		application_status = RESTART;
		//		DataNewRecordWithID(sch_appmt_dbid, SCH_STATUS, 0, 4);
		//Michelle add 130100
		//A new field is added for storing the current repeat number
		DataNewRecordWithID(sch_appmt_dbid, SCH_STATUS, 0, 5);
		DataWriteField(sch_appmt_dbid, SCH_STATUS, 0, 1, &application_status);
		DataWriteField(sch_appmt_dbid, SCH_STATUS, 1, 1, &font_size);
		DataWriteField(sch_appmt_dbid, SCH_STATUS, 2, sizeof(UWORD), (BYTE*)&count);
		count = 1000;
		DataWriteField(sch_appmt_dbid, SCH_STATUS, 3, sizeof(UWORD), (BYTE*)&count);
		DataWriteField(sch_appmt_dbid, SCH_STATUS, 4, sizeof(UWORD), (BYTE*)&count);
	}
	if (DataRecordInfo(sch_appmt_dbid, SCH_DAY_VIEW, NULL, NULL, NULL, NULL, NULL) != TRUE)
		DataNewRecordWithID(sch_appmt_dbid, SCH_DAY_VIEW, 0, 1);
}

/********************************************************
* Function:	SchedulerAppSave
* Purpose: 	This function is called to save the data in 
the application when it is called to stopped
* Scope:		application/internal
* Input:		None
* Output:		None
* Return:		TRUE if handled
FALSE if not handled
* Comment: 	None
*********************************************************/
void SchedulerAppSave()
{
	ObjectID active_form_id, control_id;
	BYTE application_status = RESTART;
	BYTE object_type, repeat_no[5];
	BYTE *buffer;
	UBYTE date[4];
	Table *table_ptr;
	BYTE  font_size;
	BYTE  *menu_text;
	void *addr;
	AlarmAttr alarm_attr;
	UWORD rec_num;
	RecordID rec_id;
	
	//Bug Fixed 5-Feb-2001
	//Delete codes
	
	if (MemoryLow)
		return;
	
	SchedulerDatabaseChecking();
#ifdef WITHSOUND
#ifdef PR31700
	SndStop();
#endif
#endif
	FormGetActiveFormID(&active_form_id);
	//Bug Fixed 5-Feb-2001
	//Delete codes
	
	SchedulerGetDayViewDate(date);
	SchedulerDayViewSaveAppmtData(&virtual_table, date);
	
	if (active_form_id == FORM_SCH_DAY_VIEW			|| 
		active_form_id == FORM_SCH_ALARM_SELECT		||
		active_form_id == FORM_SCH_PURGE		||
		active_form_id == FORM_SCH_DATE)
		application_status = DAY_VIEW;
	else if (active_form_id == FORM_SCH_MONTH)
		application_status = MONTH_VIEW;
	else if (active_form_id == FORM_SCH_WEEK)
		application_status = WEEK_VIEW;
	else if (active_form_id == FORM_SCH_TIME_SETTINGS ||
		(active_form_id == FORM_SCH_REPLAY && enter_form_id != FORM_SCH_DAY_VIEW))
		application_status = DAY_VIEW;
	else if (active_form_id == FORM_SCH_ALARM			||
		active_form_id == FORM_SCH_REC                     	||
		active_form_id == FORM_SCH_ALARM_SAVE_CHANGES		||
		active_form_id == FORM_SCH_VOICE_EXISTS			||
		active_form_id == FORM_SCH_LOW_MEMORY                  	||
		active_form_id == FORM_SCH_REPEAT			||
		active_form_id == FORM_REPEAT_SAVE_CHANGES		||
		active_form_id == FORM_REPEAT_APPLY_ALL			||
		active_form_id == FORM_CHOOSE_MONTHLY_DAY_REPEAT	||
		active_form_id == FORM_REPEAT_INVALID_INPUT		||
		(active_form_id == FORM_SCH_REPLAY && enter_form_id == FORM_SCH_VOICE_EXISTS))
	{
		application_status = DAY_VIEW;
		if (active_form_id == FORM_SCH_REC && recorded == TRUE)
		{
			alarm_settings.alarm = VOICE_ALARM;
			alarm_settings.change = TRUE;
			alarm_settings.temp_recid = rec_rec_id;
			alarm_settings.recorded = TRUE;
		}
		DataCloseRecord(alarm_settings.dbid, rec_rec_id);
		if (active_form_id == FORM_SCH_REPEAT || active_form_id == FORM_REPEAT_SAVE_CHANGES ||
			active_form_id == FORM_CHOOSE_MONTHLY_DAY_REPEAT || active_form_id == FORM_REPEAT_INVALID_INPUT)
		{
			if (repeat_settings.change)
			{
				if (repeat_settings.repeat_num != 0)
				{
					TextboxGetTextPointer(TEXTBOX_SCH_REPEAT_VALUE, &buffer);
					repeat_settings.every_info = atol((const char*)(buffer));
					if (repeat_settings.every_info != 0)
					{
						if (repeat_settings.method == REPEAT_NONE)
						{
							SchedulerDeleteRepeatDB(repeat_settings.repeat_num, FALSE);
							SchedulerSaveAndSetAlarm();
						}
						else SchedulerSaveRepeatSettings(FALSE, TRUE);
					}
				}
				else
				{
					repeat_settings.repeat_num = current_repeat_num;
					current_repeat_num++;
					TextboxGetTextPointer(TEXTBOX_SCH_REPEAT_VALUE, &buffer);
					repeat_settings.every_info = atol((const char*)(buffer));
					if (repeat_settings.every_info != 0)
						SchedulerSaveRepeatSettings(FALSE, TRUE);
				}
			}
		}
		if (active_form_id == FORM_SCH_ALARM || active_form_id == FORM_SCH_ALARM_SAVE_CHANGES ||
			active_form_id == FORM_REPEAT_APPLY_ALL)
		{
			if (virtual_table.vt_active_row != -1)
			{
				if (virtual_table.vt_items[virtual_table.vt_active_row]->repeat)
				{
					SchedulerAlarmSave();
					//	repeat_settings.alarm = time_settings.alarm;
					//	repeat_settings.alarm_num = time_settings.alarm_num;
					//	repeat_settings.alarm_time = time_settings.alarm_time;
					alarm_attr.num = time_settings.alarm_num;
					alarm_attr.time = time_settings.alarm_time;
					alarm_attr.type = time_settings.alarm;
					*((UWORD*)repeat_no) = virtual_table.vt_items[virtual_table.vt_active_row]->repeat_num;
					repeat_no[4] = 0;
					if (DataFindBinRecord(sch_repeat_dbid, F_REPEAT_NUM, 0, repeat_no, 4, &rec_id))
					{
						DataRecIDtoNum(sch_repeat_dbid, rec_id, &rec_num);
						DataOpenRecord(sch_repeat_dbid, rec_num, &rec_id, NULL);
						DataWriteField(sch_repeat_dbid, rec_id, F_ALARM_FLAG, 1, (BYTE*)"1");
						DataWriteField(sch_repeat_dbid, rec_id, F_ALARM_SETTINGS, sizeof(AlarmAttr), (BYTE*)&alarm_attr);
						DataCloseRecord(sch_repeat_dbid, rec_id);
					}
				}
			}
		}
		application_status = DAY_VIEW;
		ControlGetPushedPushButton(FORM_SCH_ALARM, 1, &control_id);
		if (alarm_settings.change == TRUE && alarm_settings.recorded == FALSE &&
			control_id == PUSHBUTTON_SCH_ALARM_VOICE && alarm_settings.alarm != VOICE_ALARM)
		{
			alarm_settings.change = TRUE;
			alarm_settings.alarm = TONE_ALARM;
		}
		SchedulerAlarmSave();
	}
	SchedulerSaveAndSetAlarm();
	DataWriteField(sch_appmt_dbid, SCH_STATUS, 0, 1, (BYTE*)&application_status);
	MenuGetMenuItem(MENU_SCH_DAY_VIEW, MENU_ITEM_ZOOM, &menu_text);
#ifdef DEBUG
	printf("\n menu_text = %s", menu_text);
#endif
	if (menu_text[0] == SCHLFONT_INT)
		font_size = SMALL_FONT;
	else font_size = MEDIUM_FONT;
	DataWriteField(sch_appmt_dbid, SCH_STATUS, 1, 1, (BYTE*)&font_size);
	DataWriteField(sch_appmt_dbid, SCH_STATUS, 2, sizeof(UWORD), (BYTE*)&alarm_count);
	DataWriteField(sch_appmt_dbid, SCH_STATUS, 3, sizeof(UWORD), (BYTE*)&current_appmt_num);
	//Michelle add 130100
	DataWriteField(sch_appmt_dbid, SCH_STATUS, 4, sizeof(UWORD), (BYTE*)&current_repeat_num);
	
	SchedulerGetDayViewDate(date);
	DataWriteField(sch_appmt_dbid, SCH_DAY_VIEW, 0, 3, (BYTE*)date);
	VTDeleteAllRowItems(&virtual_table);
	DataCloseDB(sch_appmt_dbid);
	if (FormGetObjectPointer(TABLE_SCH_DAY_VIEW, &object_type, (void**)&table_ptr) == TRUE)
		table_ptr->table_num_row = 12;
}

/********************************************************
* Function:	SchedulerAppRestore
* Purpose: 	This function is called to restore the data in 
the application when it is called to stopped
* Scope:		application/internal
* Input:		restart		whether the application is restart or not
* Output:		None
* Return:		TRUE if handled
FALSE if not handled
* Comment: 	None
*********************************************************/
void SchedulerAppRestore(BOOLEAN restart, BOOLEAN today, void *cmd_ptr)
{
	BYTE            application_status;
	BYTE            *buffer;
	UWORD           byte_read;
	RTM             time;
	UBYTE            date[4];
	SHORT           wday, nth_week;
	CountrySettings country;
	
#ifdef DEBUG_MICH
    printf("\n ===== In App Restore =====");
#endif
	
	/* global variables initialisation */
	//	duplicate = FALSE;
	new_appointment = FALSE;
	day_view_old_event.eventType = 0;
	SchInitMainGlobal();
	
	SchedulerDatabaseChecking();
	if (restart == TRUE)
		application_status = RESTART;
	else
	{
		DataGetField(sch_appmt_dbid, SCH_STATUS, 0, &buffer, &byte_read);
		application_status = *buffer;
		qfree(buffer);
	}
	
	SySetupGetCountrySettings(&country);
	DataGetField(sch_appmt_dbid, SCH_STATUS, 2, &buffer, &byte_read);
	alarm_count = *((UWORD*)buffer);
	qfree(buffer);
	
#ifdef DEBUG_MICH
	printf("\n alarm_count = %ld", alarm_count);
#endif
	
	DataGetField(sch_appmt_dbid, SCH_STATUS, 3, &buffer, &byte_read);
	current_appmt_num = *((UWORD*)buffer);
	qfree(buffer);
	
	//Michelle add 130100
	DataGetField(sch_appmt_dbid, SCH_STATUS, 4, &buffer, &byte_read);
	current_repeat_num = *((UWORD*)buffer);
	qfree(buffer);
	//end add 130100
	
	FormInitAllFormObjects(FORM_SCH_DAY_VIEW);
	FormInitAllFormObjects(FORM_SCH_WEEK);
	FormInitAllFormObjects(FORM_SCH_MONTH);
	
	if ((BYTE*)(cmd_ptr))
		application_status = RESTART;
	
	switch(application_status)
	{
	case RESTART:
		RtcGetTime(&time);
		//kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
		//RtcYMDToWday1(time.year, time.mon, time.mday, &wday, &nth_week);
		wday = Dt_Date_WDay(time.year, time.mon, time.mday);
		//kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
		
		if (country.start_of_week == SYSETUP_SUN)
			SchedulerSetDayViewDate(time.year, (time.mon + 1), time.mday, wday);
		else if (country.start_of_week == SYSETUP_MON)
		{
			if (wday == 0) wday = 6;
			else wday --;
			SchedulerSetDayViewDate(time.year, (time.mon + 1), time.mday, wday);
		}
		
		
		date[0] = (BYTE)(time.year - SYSETUP_YEAR_OFFSET);
		date[1] = (BYTE)(time.mon + 1);
		date[2] = (BYTE)(time.mday);
		SchedulerDayViewLoadAppmtDataToScreen(&virtual_table, date);
		/* determine the correct state */
		if (cmd_ptr == NULL)
		{
			FormPopupForm(FORM_SCH_DAY_VIEW);
			break;
		}
		
		if (*((BYTE*)(cmd_ptr)) == 1)
		{
			ControlSetLabel(POPUP_TRIGGER_APP_SELECT, SCHWEEK);
			ControlPopupSetSelectedItem(POPUP_TRIGGER_APP_SELECT, 2);
			SchedulerGotoPopupForm(FORM_SCH_DAY_VIEW, FALSE);
			pfree(cmd_ptr);
		}
		else if (*((BYTE*)(cmd_ptr)) == 2)
		{
			ControlSetLabel(POPUP_TRIGGER_APP_SELECT, SCHMONTH);
			ControlPopupSetSelectedItem(POPUP_TRIGGER_APP_SELECT, 3);
			SchedulerGotoPopupForm(FORM_SCH_DAY_VIEW, FALSE);
		}
		else 
		{
			FormPopupForm(FORM_SCH_DAY_VIEW);
			if (cmd_ptr)
				pfree(cmd_ptr);
		}
		break;
	case DAY_VIEW:
	case MONTH_VIEW:
	case WEEK_VIEW:
		DataGetField(sch_appmt_dbid, SCH_STATUS, 1, &buffer, &byte_read);
		virtual_table.vt_font_size = *buffer;
		qfree(buffer);
		
		
		if (today == FALSE)
		{
			DataGetField(sch_appmt_dbid, SCH_DAY_VIEW, 0, &buffer, &byte_read);
			date[0] = buffer[0];
			date[1] = buffer[1];
			date[2] = buffer[2];
			date[4] = '\0';
			qfree(buffer);
		}
		else
		{
			RtcGetTime(&time);
			date[0] = (BYTE)(time.year - SYSETUP_YEAR_OFFSET);
			date[1] = (BYTE)(time.mon + 1);
			date[2] = (BYTE)(time.mday);								
			date[3] = 0;
		}
		
		//kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
		//RtcYMDToWday1((SHORT)(date[0] + SYSETUP_YEAR_OFFSET), (SHORT)(date[1] - 1), (SHORT)(date[2]), &wday, &nth_week);
		wday = Dt_Date_WDay((SHORT)(date[0] + SYSETUP_YEAR_OFFSET), (SHORT)(date[1] - 1), (SHORT)(date[2]));
		//kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
		if (country.start_of_week == SYSETUP_MON)
		{
			if (wday == 0) wday = 6;
			else wday --;
		}
		SchedulerSetDayViewDate((SHORT)(date[0] + SYSETUP_YEAR_OFFSET), (SHORT)(date[1]), (SHORT)(date[2]), wday);
		SchedulerDayViewLoadAppmtDataToScreen(&virtual_table, date);
		
		if (application_status == WEEK_VIEW)
		{
			ControlSetLabel(POPUP_TRIGGER_APP_SELECT, SCHWEEK);
			ControlPopupSetSelectedItem(POPUP_TRIGGER_APP_SELECT, 2);
			SchedulerGotoPopupForm(FORM_SCH_DAY_VIEW, FALSE);
		}
		else if (application_status == MONTH_VIEW)
		{
			ControlSetLabel(POPUP_TRIGGER_APP_SELECT, SCHMONTH);
			ControlPopupSetSelectedItem(POPUP_TRIGGER_APP_SELECT, 3);
			SchedulerGotoPopupForm(FORM_SCH_DAY_VIEW, FALSE);
		}
		else FormPopupForm(FORM_SCH_DAY_VIEW);
		
		break;
	default: break;
	}
}



