#include <Common.h>
#include <System/SysAll.h>
#include <UI/UIAll.h>
#include <stddef.h>
#include "PCalcMain.h"
#include "DataBase.h"


/* function definitions. */

void AddConstRecord(UInt i, CharPtr symbol, CharPtr desc, CharPtr value)
{
  VoidHand h = DmNewRecord(gConstantDB, &i, sizeof(ConstDBType));
  ConstDBType* c = MemHandleLock(h);
  ConstDBType x;

  StrCopy(x.symbol, symbol);
  StrCopy(x.desc, desc);
  StrCopy(x.value, value);

  DmWrite(c, 0, &x, sizeof(ConstDBType));
  MemHandleUnlock(h);
  DmReleaseRecord(gConstantDB, i, true);
}


void ReadConstRecord(UInt i, ConstDBType* x)
{
  VoidHand h = DmQueryRecord(gConstantDB, i);
  ConstDBType* c = MemHandleLock(h);

  StrCopy(x->symbol, c->symbol);
  StrCopy(x->desc,   c->desc);
  StrCopy(x->value,  c->value);
  MemHandleUnlock(h);
}

Err ModifyConstRecord(UInt i, CharPtr symbol, CharPtr desc, CharPtr value)
{
  Err err;
  VoidHand h = DmGetRecord(gConstantDB, i);
  ConstDBType* c = MemHandleLock(h);
  ConstDBType x;

  StrCopy(x.symbol, symbol);
  StrCopy(x.desc,   desc);
  StrCopy(x.value,  value);

  err = DmWrite(c, 0, &x, sizeof(x));
  MemHandleUnlock(h);
  DmReleaseRecord(gConstantDB, i, true);

  return err;
}


void ReadProgramTitle(UInt i, CharPtr title)
{
  VoidHand h = DmQueryRecord(gProgramDB, i);
  ProgramDBType* c = MemHandleLock(h);

  StrCopy(title, c->title);
  MemHandleUnlock(h);
}


void ReadProgramCode(UInt i, CharPtr code)
{
  VoidHand h = DmQueryRecord(gProgramDB, i);
  ProgramDBType* c = MemHandleLock(h);

  StrCopy(code, c->code);
  MemHandleUnlock(h);
}


void AddProgramRecord(UInt i, CharPtr title, CharPtr code)
{
  UInt size  = sizeof(ProgramDBType) + StrLen(code);
  VoidHand h = DmNewRecord(gProgramDB, &i, size);
  ProgramDBType* c = MemHandleLock(h);

  DmWrite(c, 0, title, StrLen(title) + 1);
  DmWrite(c, offsetof(ProgramDBType, code), code, StrLen(code) + 1);

  MemHandleUnlock(h);
  DmReleaseRecord(gProgramDB, i, true);
}


Err ModifyProgramRecord(UInt i, CharPtr title, CharPtr code)
{
  Err err;
  VoidHand h
    = DmResizeRecord(gProgramDB, i, sizeof(ProgramDBType) + StrLen(code));
  ProgramDBType* c = MemHandleLock(h);

  err = DmWrite(c, 0, title, StrLen(title) + 1);
  err = DmWrite(c, offsetof(ProgramDBType, code), code, StrLen(code) + 1);

  MemHandleUnlock(h);
  DmReleaseRecord(gProgramDB, i, true);

  return err;
}
