unit Azure.CognitiveServices.FindFaces.HTTP;

interface

uses
  System.Classes,
  System.JSON,
  System.Net.URLClient,
  System.SysUtils,
  Azure.CognitiveServices.Core.HTTP,
  Azure.CognitiveServices.FindFaces.Types;

type

  TAcsFindFacesHttpBroker = class(TAcsHttpBroker<TAcsFindFacesRequest, TAcsFindFacesResponse>)
  protected
    procedure DoCustomizeContentType(const ARequest: TAcsFindFacesRequest;
      var AContentType: string); override;
    procedure DoCustomizeURI(const ARequest: TAcsFindFacesRequest;
      const AURI: TURI); override;
    procedure DoParseResponseJson(const AJSONObject: TJSONObject;
      out AResponse: TAcsFindFacesResponse); override;
    procedure DoPrepareRequestStream(const ARequest: TAcsFindFacesRequest;
      var AStream: TStream); override;
  end;

implementation

uses
  Azure.CognitiveServices.FindFaces.JSON;

procedure TAcsFindFacesHttpBroker.DoCustomizeContentType(
  const ARequest: TAcsFindFacesRequest; var AContentType: string);
begin
  inherited;
  if Length(ARequest.ImageUrl) > 0 then
    AContentType := 'application/json'
  else
    AContentType := ARequest.ImageType;
end;

procedure TAcsFindFacesHttpBroker.DoCustomizeURI(
  const ARequest: TAcsFindFacesRequest; const AURI: TURI);
begin
  inherited;
  AURI.AddParameter('CacheImage', BoolToStr(ARequest.CacheImage, True).ToLower());
end;

procedure TAcsFindFacesHttpBroker.DoParseResponseJson(
  const AJSONObject: TJSONObject; out AResponse: TAcsFindFacesResponse);
begin
  inherited;
  TAcsFindFacesJSON.Parse(AJSONObject, AResponse);
end;

procedure TAcsFindFacesHttpBroker.DoPrepareRequestStream(
  const ARequest: TAcsFindFacesRequest; var AStream: TStream);
var
  LBody: TJSONObject;
begin
  inherited;
  if Length(ARequest.ImageUrl) > 0 then
  begin
    LBody := TAcsFindFacesJSON.ToJSON(ARequest);
    try
      AStream := TStringStream.Create(LBody.ToString);
    finally
      LBody.Free;
    end;
  end
  else if Length(ARequest.ImageData) > 0 then
  begin
    AStream := TMemoryStream.Create;
    AStream.Write(ARequest.ImageData, Length(ARequest.ImageData));
    AStream.Seek(0, soFromBeginning);
  end
  else
    raise Exception.Create('Image URL or data not assigned');
end;

end.
