unit Azure.CognitiveServices.ImageOcr.HTTP;

interface

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

type

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

implementation

uses
  Azure.CognitiveServices.ImageOcr.JSON;

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

procedure TAcsImageOcrHttpBroker.DoCustomizeURI(
  const ARequest: TAcsImageOcrRequest; const AURI: TURI);
begin
  inherited;
  AURI.AddParameter('language', ARequest.Language.ToLower());
  AURI.AddParameter('CacheImage', BoolToStr(ARequest.CacheImage, True).ToLower());
  AURI.AddParameter('enhanced', BoolToStr(ARequest.Enhanced, True).ToLower());
end;

procedure TAcsImageOcrHttpBroker.DoParseResponseJson(
  const AJSONObject: TJSONObject; out AResponse: TAcsImageOcrResponse);
begin
  inherited;
  TAcsImageOcrJSON.Parse(AJSONObject, AResponse);
end;

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