program templateWebApp;

uses
  Vcl.Forms,
  XData.Web.Connection,
  WEBLib.Dialogs,
  Auth.Service in 'Auth.Service.pas',
  App.Types in 'App.Types.pas',
  ConnectionModule in 'ConnectionModule.pas' {DMConnection: TWebDataModule},
  App.Config in 'App.Config.pas',
  View.Main in 'View.Main.pas' {FViewMain: TWebForm} {*.html},
  Utils in 'Utils.pas',
  View.Login in 'View.Login.pas' {FViewLogin: TWebForm} {*.html},
  View.Test in 'View.Test.pas' {FTest: TWebForm} {*.html};

{$R *.res}

procedure DisplayLoginView(AMessage: string = ''); forward;

procedure DisplayMainView;

  procedure ConnectProc;
  begin
    if Assigned(FViewLogin) then
      FViewLogin.Free;
    TFViewMain.Display(@DisplayLoginView);
  end;

begin
  if not DMConnection.ApiConnection.Connected then
    DMConnection.ApiConnection.Open(@ConnectProc)
  else
    ConnectProc;
end;

procedure DisplayLoginView(AMessage: string = '');
begin
  AuthService.Logout;
  DMConnection.ApiConnection.Connected := False;
  if Assigned(FViewMain) then
    FViewMain.Free;
  TFViewLogin.Display(@DisplayMainView, AMessage);
end;

procedure UnauthorizedAccessProc(AMessage: string);
begin
  DisplayLoginView(AMessage);
end;

procedure AfterVerifyClientVersion(Success: Boolean; Error: string);
begin
  if not Success then
  begin
    ShowVersionMismatchAndReload(Error, DMConnection.clientVersion);
    Exit;
  end;

  if (not AuthService.Authenticated) or AuthService.TokenExpired then
    DisplayLoginView
  else
    DisplayMainView;
end;

procedure StartApplication;
begin
  AuthService.VerifyClientVersion(DMConnection.clientVersion, @AfterVerifyClientVersion);
end;

begin
  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  Application.CreateForm(TDMConnection, DMConnection);
  Application.Run;
  DMConnection.InitApp(@StartApplication, @UnauthorizedAccessProc);
end.

