unit uFieldDef;

interface

uses Rubies, DB;

var
  cFieldDef, cFieldDefs: Tvalue;

function ap_cFieldDef: Tvalue;
function ap_iFieldDef(real: TFieldDef; owner: Tvalue): Tvalue;
function ap_iFieldDefs(real: TFieldDefs; owner: Tvalue): Tvalue;
procedure Init_FieldDef;

implementation

uses uDefUtils, Pythia, uRDB;

function ap_cFieldDef: Tvalue;
begin
  result := cFieldDef;
end;

function FieldDef_alloc(This: Tvalue; real: TFieldDef): Tvalue;
begin
  result := TmpAlloc(This, real);
end;

function ap_iFieldDef(real: TFieldDef; owner: Tvalue): Tvalue;
begin
  result := FieldDef_alloc(cFieldDef, real);
  ap_owner(result, owner);
end;

function FieldDefs_alloc(This: Tvalue; real: TFieldDefs): Tvalue;
begin
  result := TmpAlloc(This, real);
end;

function ap_iFieldDefs(real: TFieldDefs; owner: Tvalue): Tvalue;
begin
  result := FieldDefs_alloc(cFieldDefs, real);
  ap_owner(result, owner);
end;

function FieldDefs_aref(This, index: Tvalue): Tvalue; cdecl;
var
  real: TFieldDefs;
  n: Integer;
begin
  real := ap_data_get_struct(This);
  n := FIX2INT(index);
  if (n < 0) or (real.Count <= n) then
    ap_raise(ap_eIndexError, sOut_of_range);

  result := ap_iFieldDef(real[n], This);
end;

function FieldDefs_get_count(This: Tvalue): Tvalue; cdecl;
var
  real: TFieldDefs;
begin
  real := ap_data_get_struct(This);
  result := INT2FIX(real.Count);
end;

function FieldDefs_add(argc: integer; argv: Pointer; This: Tvalue): Tvalue; cdecl;
var
  args: array of Tvalue;
  real: TFieldDefs;
  n: Integer;
  FieldDef: TFieldDef;
begin
  SetLength(args, argc);
  args := argv;

  real := ap_data_get_struct(This);
  FieldDef := real.AddFieldDef;
  if argc > 0 then FieldDef.Name := dl_String(args[0]);
  if argc > 1 then
  begin
    n := FIX2INT(args[1]);
    if (n < Ord(Low(TFieldType))) or (Ord(High(TFieldType)) < n) then
      ap_raise(ap_eIndexError, sOut_of_range);
    FieldDef.DataType := TFieldType(n);
  end;
  if argc > 2 then FieldDef.Size := FIX2INT(args[2]);
  if argc > 3 then FieldDef.Required := RTEST(args[3]);
  result := ap_iFieldDef(FieldDef, This);
end;

function FieldDefs_clear(This: Tvalue): Tvalue; cdecl;
var
  real: TFieldDefs;
begin
  real := ap_data_get_struct(This);
  real.Clear;
  result := This;
end;

function FieldDefs_update(This: Tvalue): Tvalue; cdecl;
var
  real: TFieldDefs;
begin
  real := ap_data_get_struct(This);
  real.Update;
  result := This;
end;

procedure Init_FieldDef;
begin
  cFieldDef := rb_define_class_under(mRDB, 'FieldDef', ap_cObject);
  DefineProp(cFieldDef, TFieldDef);

  cFieldDefs := rb_define_class_under(mRDB, 'FieldDefs', ap_cObject);
  rb_define_method(cFieldDefs, '[]', @FieldDefs_aref, 1);
  DefineAttrGet(cFieldDefs, 'count', FieldDefs_get_count);
  DefineMethod(cFieldDefs, 'add', FieldDefs_add);
  rb_define_method(cFieldDefs, 'clear', @FieldDefs_clear, 0);
  rb_define_method(cFieldDefs, 'update', @FieldDefs_update, 0);
end;

end.
