library libjpeg;

uses
  Classes, Rubies, uDefUtils, Pythia, Jpeg;

{$E so}
var
  cJpeg: Tvalue;

function ap_cJpeg: Tvalue;
begin
  result := cJpeg;
end;

function Jpeg_alloc(This: Tvalue; real: TJpegImage): Tvalue;
begin
  result := TmpAlloc(This, real);
end;

function ap_iJpeg(real: TJpegImage; owner: Tvalue): Tvalue;
begin
  result := Jpeg_alloc(cJpeg, real);
  ap_owner(result, owner);
end;

function Jpeg_new(This: Tvalue): Tvalue; cdecl;
var
  real: TJpegImage;
begin
  real := TJpegImage.Create;
  result := ObjAlloc(This, real);
  ap_obj_call_init(result, 0, nil);
end;

function Jpeg_load(This, v: Tvalue): Tvalue; cdecl;
var
  real: TJpegImage;
  stream: TStream;
begin
  real := ap_data_get_struct(This);
  case RTYPE(v) of
  T_STRING:
    try
      real.LoadFromFile(dl_String(v));
    except
      on E: EFOpenError do
        ap_raise(ap_eIOError, E.message);
    end;
  T_DATA:
    try
      ap_data_get_object(v, TStream, stream);
      real.LoadFromStream(stream);
    except
      on E: EReadError do;
    end;
  else
    ap_raise(ap_eArgError, sWrong_arg_type);
  end;
  result := This;
end;

function Jpeg_save(This, v: Tvalue): Tvalue; cdecl;
var
  real: TJpegImage;
  stream: TStream;
begin
  real := ap_data_get_struct(This);
  case RTYPE(v) of
  T_STRING:
    try
      real.SaveToFile(dl_String(v));
    except
      on E: EFCreateError do
        ap_raise(ap_eIOError, E.message);
    end;
  T_DATA:
    try
      ap_data_get_object(v, TStream, stream);
      real.SaveToStream(stream);
    except
      on E: EWriteError do;
    end;
  else
    ap_raise(ap_eArgError, sWrong_arg_type);
  end;
  result := v;
end;

function Jpeg_assign(This, v: Tvalue): Tvalue; cdecl;
var
  real: TJpegImage;
  source: TPersistent;
begin
  real := ap_data_get_struct(This);
  ap_data_get_object(v, TPersistent, source);
  real.Assign(source);
  result := v;
end;

procedure Init_jpeg;
begin
  PhiStart;

  cJpeg := rb_define_class_under(ap_mPhi, 'Jpeg', ap_cPersistent);
  DefineProp(cJpeg, TJpegImage);

  rb_define_singleton_method(cJpeg, 'new', @Jpeg_new, 0);
  rb_define_method(cJpeg, 'load', @Jpeg_load, 1);
  rb_define_method(cJpeg, 'save', @Jpeg_save, 1);
  rb_define_method(cJpeg, 'assign', @Jpeg_assign, 1);
end;

exports
  ap_cJpeg,
  ap_iJpeg,
  Init_jpeg;

end.
