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


/* globals. */
static Int     gEditConstRecord;
static Boolean gAddRecord;

/* prototypes for internal functions. */
static Boolean CheckConstData(CharPtr*, CharPtr*, CharPtr*);


/* functions. */

Boolean EditConstFormHandleEvent(EventPtr event)
{
  Boolean handled = false;
  FormPtr form = FrmGetActiveForm();

  switch (event->eType) {
  case frmOpenEvent:
    if (!gAddRecord) {
      ConstDBType c;

      ReadConstRecord(gEditConstRecord, &c);
      SetFieldText(fieldEditConstSymbolID, c.symbol);
      SetFieldText(fieldEditConstDescID,   c.desc);
      SetFieldText(fieldEditConstValueID,  c.value);
    } else {
      SetFieldText(fieldEditConstSymbolID, "");
      SetFieldText(fieldEditConstDescID,   "");
      SetFieldText(fieldEditConstValueID,  "");
    }
    FrmDrawForm(form);
    handled = true;
    break;

  case ctlSelectEvent:
    switch(event->data.ctlSelect.controlID) {
    case buttonEditConstOkID:
      {
	CharPtr symbol = FldGetTextPtr(GetObjectPtr(fieldEditConstSymbolID));
	CharPtr desc   = FldGetTextPtr(GetObjectPtr(fieldEditConstDescID));
	CharPtr value  = FldGetTextPtr(GetObjectPtr(fieldEditConstValueID));

	if (CheckConstData(&symbol, &desc, &value)) {
	  if (gAddRecord) {
	    AddConstRecord(gEditConstRecord, symbol, desc, value);
	  } else {
	    ModifyConstRecord(gEditConstRecord, symbol, desc, value);
	  }
	  FrmGotoForm(formSelectConstID);
	}
      }
      handled = true;
      break;
     
    case buttonEditConstCancelID:
      FrmGotoForm(formSelectConstID);
      handled = true;
      break;
    }

  case menuEvent:
    handled = HandleCommonEditMenu(event->data.menu.itemID);
    break;

  case nilEvent:
    handled = true;
    break;
  }

  return handled;
}


void SetEditConstRecord(Int i, Boolean add)
{
  gEditConstRecord = i;
  gAddRecord = add;
}


static Boolean CheckConstData(CharPtr* symbol, CharPtr* desc, CharPtr* value)
{
  SkipLeadingSpace(symbol);

  if (StrLen(*symbol) == 0) {
    FrmCustomAlert(alertInformID, "SYMBOL :", "No data.", "");
    return false;
  }
  if (StrLen(*desc) == 0) {
    FrmCustomAlert(alertInformID, "DESC :",  "No data.", "");
    return false;
  }

  if (**symbol != '$') {
    if (FrmCustomAlert(alertConfirmID, "SYMBOL :", "No leading '$' char.",
		       "Are you sure?") == 1) return true;
  }

  if (StrLen(*value) == 0) {
    FrmCustomAlert(alertInformID, "VALUE :",  "No data.", "");
    return false;
  }


  return true;
}
