/* OpenPGP for Palm III */
#pragma pack(2)
#include <Common.h>
#include <System/SysAll.h>
#include <UI/UIAll.h>
#include <System/SysEvtMgr.h>

#include "opgptst.h"

static Boolean opgptst(EventPtr event);
void RunOpenPGP(void);

FormPtr form;

static int StartApplication(void)
{
  int error;

  FrmGotoForm(fmain);
  return 0;
}

static void EventLoop(void)
{
  short err;
  int formID;
  FormPtr form;
  EventType event;

  do {
    EvtGetEvent(&event, 200);

    if (SysHandleEvent(&event))
      continue;
    if (MenuHandleEvent((void *) 0, &event, &err))
      continue;

    if (event.eType == frmLoadEvent) {
      formID = event.data.frmLoad.formID;
      form = FrmInitForm(formID);
      FrmSetActiveForm(form);
      switch (formID) {
      case fmain:
        FrmSetEventHandler(form, (FormEventHandlerPtr) opgptst);
        break;
      }
    }
    FrmDispatchEvent(&event);
  } while (event.eType != appStopEvent);
}

static void StopApplication(void)
{

}

DWord PilotMain(Word cmd, Ptr cmdPBP, Word launchFlags)
{
  int error;

  if (cmd == sysAppLaunchCmdNormalLaunch) {
    if (error = StartApplication())
      return error;
    EventLoop();     

    StopApplication();

  }
  return 0;
}

static Boolean opgptst(EventPtr event)
{
  int handled = 0;
  switch (event->eType) {
  case frmOpenEvent:

    form = FrmGetActiveForm();

    FrmDrawForm(form);

    /* should be based on clipboard content */

    CtlSetValue(FrmGetObjectPtr(form, FrmGetObjectIndex(form, bdec)), 1);
    handled = 1;
    break;

  case ctlSelectEvent:         // A control button was pressed and released.

    switch (event->data.ctlEnter.controlID) {
    case brun:
      RunOpenPGP();
      handled = 1;
      break;
    }
    break;

  case menuEvent:
    switch (event->data.menu.itemID) {
    case mabout:
      FrmAlert(aabout);
      break;
    case madv:
      {
        FormPtr renf;

        renf = FrmInitForm(fadvset);
        if (!renf)
          break;
        CtlSetValue(FrmGetObjectPtr(renf, FrmGetObjectIndex(renf, b3des)), 1);
        CtlSetValue(FrmGetObjectPtr(renf, FrmGetObjectIndex(renf, bsha)), 1);
        FrmDoDialog(renf);
        FrmDeleteForm(renf);
      }

      break;
    }
    handled = 1;
    break;

  case nilEvent:
    handled = 1;
    break;
  }
  return handled;
}
