unit ConnectionModule;

interface

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

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

  public
    const clientVersion = '0.0.1';
    procedure InitApp(SuccessProc: TSuccessProc;
      UnauthorizedAccessProc: TUnauthorizedAccessProc);
  end;

var
  DMConnection: TDMConnection;

implementation

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

{%CLASSGROUP 'Vcl.Controls.TControl'}

{$R *.dfm}

procedure TDMConnection.ApiConnectionError(Error: TXDataWebConnectionError);
var
  errorMsg: string;
begin
  errorMsg := Error.ErrorMessage;
  if errorMsg = '' then
    errorMsg := 'Connection error';

  if Assigned(FUnauthorizedAccessProc) then
    FUnauthorizedAccessProc(errorMsg)
  else
    ShowMessage(errorMsg);
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);
var
  errorMsg: string;
begin
  errorMsg := Error.ErrorMessage;
  if errorMsg = 'Error connecting to XData server' then
    errorMsg := 'Error connecting to server. Please try again later.';

  if Assigned(FUnauthorizedAccessProc) then
    FUnauthorizedAccessProc(errorMsg)
  else
    ShowMessage(errorMsg);
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;


end.
