unit OpenAPI.Utils;

interface

uses
  SysUtils,
  OpenApi.Types,
  XData.JSchema.Classes;

type
  TOpenAPIUtils = class
  public
    class function NewArraySchema(ItemSchema: TJsonSchema = nil): TArraySchema;
    class function NewBooleanSchema: TBooleanSchema;
    class function NewFileSchema: TFileSchema;
    class function NewIntegerSchema(const Format: string = ''): TIntegerSchema;
    class function NewObjectSchema: TObjectSchema;
    class function NewStringSchema(const Format: string = ''): TStringSchema;
    class procedure SetNameReference(var Schema: TJsonSchema; const SchemaRef: string);
  end;

implementation

{ TOpenAPIUtils }

class function TOpenAPIUtils.NewArraySchema(ItemSchema: TJsonSchema): TArraySchema;
begin
  result := TArraySchema.Create;
  if ItemSchema <> nil then
    result.ItemSchemas.Add(ItemSchema);
end;

class function TOpenAPIUtils.NewBooleanSchema: TBooleanSchema;
begin
  result := TBooleanSchema.Create;
end;

class function TOpenAPIUtils.NewFileSchema: TFileSchema;
begin
  result := TFileSchema.Create;
end;

class function TOpenAPIUtils.NewIntegerSchema(const Format: string = ''): TIntegerSchema;
begin
  result := TIntegerSchema.Create;
  result.Format := Format;
end;

class function TOpenAPIUtils.NewObjectSchema: TObjectSchema;
begin
  result := TObjectSchema.Create;
end;

class function TOpenAPIUtils.NewStringSchema(const Format: string): TStringSchema;
begin
  result := TStringSchema.Create;
  result.Format := Format;
end;

class procedure TOpenAPIUtils.SetNameReference(var Schema: TJsonSchema; const SchemaRef: string);
var
  nameRef: TNameReferenceSchema;
begin
  nameRef := TNameReferenceSchema.Create(SchemaRef);
  if Assigned(Schema) and (Schema is TArraySchema) then
  begin
    TArraySchema(Schema).ItemSchemas.Clear;
    TArraySchema(Schema).ItemSchemas.Add(nameRef);
  end
  else
  begin
    Schema.Free;
    Schema := nameRef;
  end;
end;

end.
