 unit ConnectionModule;

interface

uses
  System.SysUtils, System.Classes, WEBLib.Modules, WEBLib.Dialogs,
  App.Types, App.Config, XData.Web.Connection, 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.15.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);
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 = '' then
    errorMsg := 'Connection error';

  if errorMsg = 'Error connecting to XData server' then
    ShowMessage( 'Error connecting to kgOrdersServer' + sLineBreak + 'Please contact EM Systems support' )
  else 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;

procedure TDMConnection.SetClientConfig(Callback: TVersionCheckCallback);
begin
  XDataWebClient1.Connection := AuthConnection;
  console.log('ClientConfig');
  XDataWebClient1.RawInvoke('IAuthService.VerifyVersion', [clientVersion],
    procedure(Response: TXDataClientResponse)  //this is the success callback
    var
      jsonResult: TJSObject;
      error: string;
    begin
      jsonResult := TJSObject(Response.Result);

      if jsonResult.HasOwnProperty('error') then
      begin
        error := string(jsonResult['error']);
        Callback(False, error);
      end
      else
        Callback(True, '');

    end,
    procedure(Error: TXDataClientError)  //this is the error callback
    begin
      Callback(False, Error.ErrorMessage);
    end);
end;


end.
