
#include <Common.h>
#include <System/SysAll.h>
#include <UI/UIAll.h>
#include "resource.h"
#include "PCalcMain.h"
#include "SelProgForm.h"
#include "EditProgForm.h"
#include "DataBase.h"
#include "Misc.h"


/* prototypes. */
static void ProgramListDrawFunc(UInt, RectanglePtr, CharPtr*);
static void UpdateProgramList(void);


/* define functions. */
Boolean SelProgFormHandleEvent(EventPtr event)
{
  Boolean handled = false;
  FormPtr form = FrmGetActiveForm();

  switch (event->eType) {
  case frmOpenEvent:
    UpdateProgramList();
    FrmDrawForm(form);
    handled = true;
    break;

  case frmUpdateEvent:
    UpdateProgramList();
    FrmEraseForm(form);
    // The form is automatically redrawn by PalmOS.
    break;

  case ctlSelectEvent:
    {
      ListPtr ProgramListPtr = GetObjectPtr(listSelectProgTitleID);
      Int sel = LstGetSelection(ProgramListPtr);
      Int num = LstGetNumberOfItems(ProgramListPtr);

      switch(event->data.ctlSelect.controlID) {
      case buttonSelectProgAddID:
	if (sel >= 0) {
	  PresetEditProgFormParam(sel, true, -1);
	  FrmPopupForm(formEditProgID);
	} else {
	  SndPlaySystemSound(sndError);
	}
	handled = true;
	break;

      case buttonSelectProgEditID:
	if ((sel >= 0) && (sel < num - 1)) {
	  PresetEditProgFormParam(sel, false, -1);
	  FrmPopupForm(formEditProgID);
	} else {
	  SndPlaySystemSound(sndError);
	}
	handled = true;
	break;

      case buttonSelectProgDelID:
	if ((sel >= 0) && (sel < num - 1)) {
	  if (FrmCustomAlert(alertConfirmID,
			     "Delete the program.",
			     "Are you sure?", "") == 1) {
	    DmRemoveRecord(gProgramDB, sel);
	    UpdateProgramList();
	    FrmDrawForm(form);
	  }
	} else {
	  SndPlaySystemSound(sndError);
	}
	handled = true;
	break;

      case buttonSelectProgOkID:
	FrmGotoForm(formMainID);
	handled = true;
	break;
      }
    }

  case nilEvent:
    handled = true;
    break;
  }

  return handled;
}


static void ProgramListDrawFunc(UInt i, RectanglePtr bounds, CharPtr* data)
{
  Char s[32];

  if (i < DmNumRecords(gProgramDB)) {
    ReadProgramTitle(i, s);
    WinDrawChars(s, StrLen(s), bounds->topLeft.x, bounds->topLeft.y);
  } else {
    StrPrintF(s, "-- END OF LIST --");
    WinDrawChars(s, StrLen(s), bounds->topLeft.x
		 + 0.5 * (bounds->extent.x - FntCharsWidth(s, StrLen(s))),
		 bounds->topLeft.y);
  }
}


static void UpdateProgramList(void)
{
  ListPtr ProgramList = GetObjectPtr(listSelectProgTitleID);

  LstSetListChoices(ProgramList,  NULL, DmNumRecords(gProgramDB) + 1);
  LstSetDrawFunction(ProgramList, ProgramListDrawFunc);
}
