unit OpenAPI.Json.Converters;

interface

uses
  SysUtils, Rtti,
  Bcl.Json.Converters, Bcl.Json.Writer, Bcl.Json.Reader;

type
  TOpenAPIJsonConverters = class(TJsonConverters)
  public
    procedure AfterConstruction; override;
  end;

  TJsonSchemaConverterFactory = class(TInterfacedObject, IJsonConverterFactory)
  strict protected
    function CreateConverter(AConverters: TJsonConverters; const ATypeToken: TTypeToken): IJsonTypeConverter;
  end;

  TJsonSchemaConverter = class(TInterfacedObject, IJsonTypeConverter)
  protected
    procedure WriteJson(const Writer: TJsonWriter; const Value: TValue);
    procedure ReadJson(const Reader: TJsonReader; var Value: TValue);
  end;

implementation

uses
  XData.JSchema.Classes, XData.JSchema.Writer;

{ TOpenAPIJsonConverters }

procedure TOpenAPIJsonConverters.AfterConstruction;
begin
  inherited;
  AddFactory(TJsonSchemaConverterFactory.Create);
end;

{ TJsonSchemaConverterFactory }

function TJsonSchemaConverterFactory.CreateConverter(AConverters: TJsonConverters;
  const ATypeToken: TTypeToken): IJsonTypeConverter;
begin
  if ATypeToken.IsClass and ATypeToken.GetClass.InheritsFrom(TJsonSchema) then
    result := TJsonSchemaConverter.Create
  else
    result := nil;
end;

{ TJsonSchemaConverter }

procedure TJsonSchemaConverter.ReadJson(const Reader: TJsonReader; var Value: TValue);
begin
  raise ENotImplemented.Create(ClassName);
end;

procedure TJsonSchemaConverter.WriteJson(const Writer: TJsonWriter; const Value: TValue);
var
  schemaWriter: TJSchemaWriter;
begin
  schemaWriter := TJSchemaWriter.Create(Writer);
  try
    schemaWriter.WriteSchema(TJsonSchema(Value.AsObject));
  finally
    schemaWriter.Free;
  end;
end;

end.

