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


/* prototypes. */
static void ConstListDrawFunc(UInt, RectanglePtr, CharPtr*);
static void UpdateConstList(void);


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

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

 case ctlSelectEvent:
   {
     ListPtr ConstListPtr = GetObjectPtr(listSelectConstDescID);
     Int sel = LstGetSelection(ConstListPtr);
     Int num = LstGetNumberOfItems(ConstListPtr);

     switch(event->data.ctlSelect.controlID) {
     case buttonSelectConstAddID:
       if (sel >= 0) {
         SetEditConstRecord(sel, true);
         FrmGotoForm(formEditConstID);
       } else {
         SndPlaySystemSound(sndError);
       }
       handled = true;
       break;

     case buttonSelectConstEditID:
       if ((sel >= 0) && (sel < num - 1)) {
         SetEditConstRecord(sel, false);
         FrmGotoForm(formEditConstID);
       } else {
         SndPlaySystemSound(sndError);
       }
       handled = true;
       break;

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

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

   case nilEvent:
     handled = true;
     break;
 }

 return handled;
}


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

 if (i < DmNumRecords(gConstantDB)) {
   ReadConstRecord(i, &c);
   WinDrawChars(c.desc, StrLen(c.desc), 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 UpdateConstList(void)
{
 ListPtr ConstList = GetObjectPtr(listSelectConstDescID);

 LstSetListChoices(ConstList,  NULL, DmNumRecords(gConstantDB) + 1);
 LstSetDrawFunction(ConstList, ConstListDrawFunc);
}