#include "project.h"


int prefs[PrefNum] = { 1, 1, 1, 1, 1, 1, 1,1 };

void
preferences_done (void)
{
  FieldPtr fp;
  FormPtr formptr;
  UInt16 index;
  VoidHand mh;
  VoidPtr p;
  int i;


  formptr = FrmGetFormPtr (PrefForm);
  if (!formptr)
    return;

  for (i = 0; i < PrefNum; ++i)
    {
      index = FrmGetObjectIndex (formptr, PrefBase + i);
      fp = FrmGetObjectPtr (formptr, index);
      if (!fp)
        return;

      mh = (VoidHand) FldGetTextHandle (fp);
      FldSetTextHandle (fp, NULL);
      if (mh)
        {

          p = MemHandleLock (mh);

          prefs[i] = StrAToI (p);

          MemHandleUnlock (mh);

        }

      hifi_me (HIFI_CLASS_DISPLAY, displayunit);
    }









  PrefSetAppPreferences (APPID, 0, 10, prefs, sizeof (prefs), 1);
}

void
preferences_init (void)
{
  UInt16 size;

  size = sizeof (prefs);

  if (PrefGetAppPreferences (APPID, 0, prefs, &size, 1) == noPreferenceFound)
    return;


  return;

}

void
preferences_open (void)
{
  FieldPtr fp;
  FormPtr formptr;
  UInt16 index;
  VoidHand mh;
  VoidPtr p;
  int i;

  preferences_init ();


  formptr = FrmGetFormPtr (PrefForm);
  if (!formptr)
    return;



  for (i = 0; i < PrefNum; ++i)
    {
      index = FrmGetObjectIndex (formptr, PrefBase + i);
      fp = FrmGetObjectPtr (formptr, index);
      if (!fp)
        return;

      mh = (VoidHand) FldGetTextHandle (fp);
      FldSetTextHandle (fp, NULL);
      if (!mh)
        {
          mh = MemHandleNew (10);
        }

      if (MemHandleSize (mh) < 10)
        {
          MemHandleResize (mh, 10);
        }

      p = MemHandleLock (mh);

      sprintf (p, "%d", prefs[i]);

      MemHandleUnlock (mh);

      FldSetTextHandle (fp, (Handle) mh);
      FldDrawField (fp);

    }

}



void
preferences_dispatch (EventType * e)
{

  switch (e->eType)
    {
    case frmOpenEvent:
      preferences_open ();
      break;
    case ctlSelectEvent:

      switch (e->data.ctlEnter.controlID)
        {
        case PrefDone:
          preferences_done ();
          FrmGotoForm (SystemForm);
          break;
        }
      break;


    }

}
