unit Azure.CognitiveServices.ImageOcr.JSON;

interface

uses
  System.Generics.Collections,
  System.JSON,
  System.SysUtils,
  Azure.CognitiveServices.ImageOcr.Types;

type

  TAcsImageOcrJSON = class
  public
    class procedure Parse(const AObject: TJSONObject; var AData: TAcsImageOcrResponse); overload;
    class procedure Parse(const AJSONArray: TJSONArray; var AData: TArray<TAcsImageOcrCandidates>); overload;
    class procedure Parse(const AJSONObject: TJSONObject; var AData: TAcsImageOcrCandidates); overload;
    class function ToJSON(const AData: TAcsImageOcrRequest): TJSONObject; overload;
  end;

implementation

class procedure TAcsImageOcrJSON.Parse(const AObject: TJSONObject;
  var AData: TAcsImageOcrResponse);
begin
  AData.TrackingId := AObject.GetValue<string>('TrackingId');
  if not AObject.TryGetValue<string>('CacheId', AData.CacheId) then
    AData.CacheId := EmptyStr;
  AData.Language := AObject.GetValue<string>('Language');
  AData.Text := AObject.GetValue<string>('Text');
  Parse(TJSONArray(AObject.GetValue('Candidates')), AData.Candidates);
end;

class procedure TAcsImageOcrJSON.Parse(const AJSONArray: TJSONArray;
  var AData: TArray<TAcsImageOcrCandidates>);
var
  LIndex: Integer;
begin
  SetLength(AData, AJSONArray.Count);
  for LIndex := 0 to AJSONArray.Count - 1 do
    Parse(TJSONObject(AJSONArray[LIndex]), AData[LIndex]);
end;

class procedure TAcsImageOcrJSON.Parse(const AJSONObject: TJSONObject;
  var AData: TAcsImageOcrCandidates);
begin
  AData.Text := AJSONObject.GetValue<string>('Text');
  AData.Confidence := AJSONObject.GetValue<Double>('Confidence');
end;

class function TAcsImageOcrJSON.ToJSON(const AData: TAcsImageOcrRequest): TJSONObject;
begin
  Result := TJSONObject.Create;
  if Length(AData.ImageUrl) <= 0 then
    Exit;
  Result.AddPair('DataRepresentation', 'URL');
  Result.AddPair('Value', AData.ImageUrl);
end;

end.
