unit XData.Json.Converters;

interface

uses
  System.Rtti, System.SysUtils,
  Aurelius.Events.Manager, // remove this later when unifying TEvent<T>
  Aurelius.Types.Blob,
  Bcl.Json.Converters,
  Bcl.Json.Reader,
  Bcl.Json.Writer,
  XData.Aurelius.Model,
  XData.Json.Converter;

type
  TXDataJsonConverters = class;

  TXDataJsonConvertersCreateArgs = class
  strict private
    {$IFDEF AUTOREFCOUNT}[Weak]{$ENDIF}
    FConverters: TXDataJsonConverters;
  public
    constructor Create(AConverters: TXDataJsonConverters);
    property Converters: TXDataJsonConverters read FConverters;
  end;
  TXDataJsonConvertersCreateProc = TProc<TXDataJsonConvertersCreateArgs>;

  TXDataJsonConverters = class(TJsonConverters)
  private
    class var FOnGlobalCreate: TEvent<TXDataJsonConvertersCreateProc>;
  public
    class property OnGlobalCreate: TEvent<TXDataJsonConvertersCreateProc> read FOnGlobalCreate;
  private
    FEntityFactory: TXDataJsonConverterFactory;
    procedure NotifyConvertersCreated;
  public
    constructor Create(AModel: TXDataAureliusModel); reintroduce;
    property EntityFactory: TXDataJsonConverterFactory read FEntityFactory;
  end;

implementation

uses
  Aurelius.Json.BlobConverter,
  XData.Json.CriteriaResultConverter;

{ TXDataJsonConverters }

constructor TXDataJsonConverters.Create(AModel: TXDataAureliusModel);
begin
  inherited Create;
  Self.ObjectFactory := AModel.Explorer.ObjectFactory;
  AddFactory(TJsonConverterStaticFactory<TJsonBlobConverter>.Factory);
  AddFactory(TJsonCriteriaResultConverterFactory.Create);
  FEntityFactory := TXDataJsonConverterFactory.Create(AModel);
  NotifyConvertersCreated;
  AddFactory(FEntityFactory);
end;

procedure TXDataJsonConverters.NotifyConvertersCreated;
var
  Args: TXDataJsonConvertersCreateArgs;
  Listener: TXDataJsonConvertersCreateProc;
begin
  if OnGlobalCreate.HasListeners then
  begin
    Args := TXDataJsonConvertersCreateArgs.Create(Self);
    try
      for Listener in OnGlobalCreate.Listeners do
        Listener(Args);
    finally
      Args.Free;
    end;
  end;
end;

{ TXDataJsonConvertersCreateArgs }

constructor TXDataJsonConvertersCreateArgs.Create(
  AConverters: TXDataJsonConverters);
begin
  FConverters := AConverters;
end;

end.
