unit Azure.CognitiveServices.ImageModeration.HTTP;

interface

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

type

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

implementation

uses
  Azure.CognitiveServices.ImageModeration.JSON;

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

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

procedure TAcsImageModerationHttpBroker.DoParseResponseJson(
  const AJSONObject: TJSONObject;
  out AResponse: TAcsImageModerationResponse);
begin
  inherited;
  TAcsImageModerationJSON.Parse(TJSONObject(AJSONObject), AResponse);
end;

procedure TAcsImageModerationHttpBroker.DoPrepareRequestStream(
  const ARequest: TAcsImageModerationRequest; var AStream: TStream);
var
  LBody: TJSONObject;
begin
  inherited;
  if Length(ARequest.ImageUrl) > 0 then
  begin
    LBody := TAcsImageModerationJSON.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.
