unit ConnectionModule;

interface

uses
  System.SysUtils, System.Classes, WEBLib.Modules, XData.Web.Connection,
  App.Types, App.Config, XData.Web.Client;

type
  TDMConnection = class(TWebDataModule)
    ApiConnection: TXDataWebConnection;
    AuthConnection: TXDataWebConnection;
    XDataWebClient1: TXDataWebClient;
    procedure ApiConnectionError(Error: TXDataWebConnectionError);
    procedure ApiConnectionRequest(Args: TXDataWebConnectionRequest);
    procedure ApiConnectionResponse(Args: TXDataWebConnectionResponse);
    procedure AuthConnectionError(Error: TXDataWebConnectionError);
  private
    FUnauthorizedAccessProc: TUnauthorizedAccessProc;

  public
    const clientVersion = '0.9.14.1';
    procedure InitApp(SuccessProc: TSuccessProc;
      UnauthorizedAccessProc: TUnauthorizedAccessProc);
    procedure SetClientConfig(Callback: TVersionCheckCallback);
  end;

var
  DMConnection: TDMConnection;

implementation

uses
  JS, Web,
  XData.Web.Request,
  XData.Web.Response,
  Auth.Service,
  View.ErrorPage;

{%CLASSGROUP 'Vcl.Controls.TControl'}

{$R *.dfm}

procedure TDMConnection.ApiConnectionError(Error: TXDataWebConnectionError);
begin
  TFViewErrorPage.DisplayConnectionError(Error);
end;


procedure TDMConnection.ApiConnectionRequest(Args: TXDataWebConnectionRequest);
begin
  if AuthService.Authenticated then
    Args.Request.Headers.SetValue('Authorization', 'Bearer ' + AuthService.GetToken);
end;


procedure TDMConnection.ApiConnectionResponse(
  Args: TXDataWebConnectionResponse);
begin
  if Args.Response.StatusCode = 401 then
    FUnauthorizedAccessProc(Format('%d: %s',[Args.Response.StatusCode, Args.Response.ContentAsText]));
end;


procedure TDMConnection.AuthConnectionError(Error: TXDataWebConnectionError);
begin
  TFViewErrorPage.DisplayConnectionError(Error);
end;


procedure TDMConnection.InitApp(SuccessProc: TSuccessProc;
  UnauthorizedAccessProc: TUnauthorizedAccessProc);

  procedure ConfigLoaded(Config: TAppConfig);
  begin
    if Config.AuthUrl <> '' then
      AuthConnection.URL := Config.AuthUrl;

    if Config.ApiUrl <> '' then
      ApiConnection.URL := Config.ApiUrl;

    AuthConnection.Open(SuccessProc);
  end;

begin
  FUnauthorizedAccessProc := UnauthorizedAccessProc;
  LoadConfig(@ConfigLoaded);
end;


procedure TDMConnection.SetClientConfig(Callback: TVersionCheckCallback);
begin
  XDataWebClient1.Connection := AuthConnection;

  XDataWebClient1.RawInvoke('IAuthService.VerifyVersion', [clientVersion],
    procedure(Response: TXDataClientResponse)
    var
      jsonResult: TJSObject;
      error: string;
    begin
      jsonResult := TJSObject(Response.Result);

      if jsonResult.HasOwnProperty('error') then
        error := string(jsonResult['error'])
      else
        error := '';

      if error <> '' then
        Callback(False, error)
      else
        Callback(True, '');
    end);
end;


end.
