unit ServerMethodsUnit1;

interface

uses System.SysUtils, System.Classes, Datasnap.DSServer, Datasnap.DSAuth,
  Data.DBXMSSQL, Data.FMTBcd, Data.DB, Data.SqlExpr, Datasnap.Provider, Data.DBXJSON,
  Data.DBXInterBase, Vcl.Dialogs;

type
  TServerMethods1 = class(TDSServerModule)
    demos_interbase: TSQLConnection;
    Imagenes_Interbase: TSQLQuery;
    dspImagenes_Interbase: TDataSetProvider;
    Imagenes_InterbaseIDBANNER: TIntegerField;
    Imagenes_InterbaseBANNER: TBlobField;
    GetImageBanner_Interbase: TSQLQuery;
    dspGetImageBanner_Interbase: TDataSetProvider;
    GetImageBanner_InterbaseBANNER: TBlobField;
    procedure demos_interbaseBeforeConnect(Sender: TObject);
  private
    { Private declarations }
    function GetImagenBannerAsStream(ASQLQuery: TSQLQuery; AIDBanner: Integer): TStream; overload;
  public
    { Public declarations }
    function EchoString(Value: string): string;
    function ReverseString(Value: string): string;
    function GetImagenBannerAsJSON(AIDBanner: Integer): TJSONArray;
    function GetImagenBannerAsStream(AIDBanner: Integer): TStream; overload;
  end;

implementation

{$R *.dfm}

uses System.StrUtils, UMainServer, Data.DBXJSONCommon;


function TServerMethods1.GetImagenBannerAsStream(ASQLQuery: TSQLQuery; AIDBanner: Integer): TStream;

var
  stream: TMemoryStream;
begin
  if (ASQLQuery.Active) then ASQLQuery.Close();

  ASQLQuery.ParamByName('IDBanner').Value := AIDBanner;
  ASQLQuery.Open();

  stream := TMemoryStream.Create;

  stream.WriteData(ASQLQuery.FieldByName('Banner').AsBytes,
                   Length(ASQLQuery.FieldByName('Banner').AsBytes));
  //stream.SaveToFile('test_ahora.jpg');
  stream.Seek(0, System.Classes.TSeekOrigin.soBeginning);

  ASQLQuery.Close();

  Result:= stream;
end;

function TServerMethods1.GetImagenBannerAsJSON(AIDBanner: Integer): TJSONArray;
var
  stream: TStream;
begin
  stream:= GetImagenBannerAsStream(AIDBanner);
  try
    Result:= TDBXJSONTools.StreamToJSON(stream, 0, stream.Size);
  finally
    stream.Free;
  end;
end;

function TServerMethods1.GetImagenBannerAsStream(AIDBanner: Integer): TStream;
begin
  Result:= GetImagenBannerAsStream(GetImageBanner_Interbase, AIDBanner);
end;

procedure TServerMethods1.demos_interbaseBeforeConnect(Sender: TObject);
begin
  demos_interbase.Params.Values['Database'] := MainServer.GetPath;
end;

function TServerMethods1.EchoString(Value: string): string;
begin
  Result := Value;
end;

function TServerMethods1.ReverseString(Value: string): string;
begin
  Result := System.StrUtils.ReverseString(Value);
end;

end.

