unit App.Config;

interface

uses
  JS, XData.Web.Connection, XData.Web.Request, XData.Web.Response;

type
  TAppConfig = class
  private
    FApiUrl: string;
  public
    constructor Create;
    property ApiUrl: string read FApiUrl write FApiUrl;
  end;

  TConfigLoadedProc = reference to procedure(Config: TAppConfig);
  procedure LoadConfig(LoadProc: TConfigLoadedProc);

implementation

constructor TAppConfig.Create;
begin
  FApiUrl := '';
end;

procedure LoadConfig(LoadProc: TConfigLoadedProc);
var
  Conn: TXDataWebConnection;
begin
  Conn := TXDataWebConnection.Create(nil);
  Conn.SendRequest(
    THttpRequest.Create('config/config.json'),
    procedure(Response: IHttpResponse)
    var
      Obj: TJSObject;
      Config: TAppConfig;
    begin
      Config := TAppConfig.Create;
      try
        if Response.StatusCode = 200 then
        begin
          Obj := TJSObject(TJSJSON.parse(Response.ContentAsText));
          if JS.toString(Obj['apiBaseUrl']) <> '' then
            Config.ApiUrl := JS.toString(Obj['apiBaseUrl']);
        end;
        LoadProc(Config);
        Config.Free;
      except
        Config.Free;
        LoadProc(TAppConfig.Create); // fallback empty config
      end;
    end,
    procedure
    begin
      LoadProc(TAppConfig.Create); // fallback if request fails
    end
  );
end;

end.

