unit TestPageForm;

interface

uses
  System.SysUtils,
  System.Classes,
  JS,
  Web,
  WEBLib.Graphics,
  WEBLib.Controls,
  WEBLib.Forms,
  WEBLib.Dialogs,
  Vcl.Controls,
  WEBLib.StdCtrls,
  Sphinx.WebLogin,
  Test.DistributionConfig,
  TestApp.Shared;

type
  TTestPageForm = class(TWebForm)
    lblTitle: TWebLabel;
    lblStatus: TWebLabel;
    btnLogout: TWebButton;
    btnLoginAgain: TWebButton;
    SphinxLogin1: TSphinxWebLogin;
    procedure btnLogoutClick(Sender: TObject);
    procedure btnLoginAgainClick(Sender: TObject);
    procedure SphinxLogin1UserLoggedIn(Args: TUserLoggedInArgs);
    [async]
    procedure WebFormCreate(Sender: TObject);
  private
    procedure ApplyLoggedInState;
    procedure ApplyLoggedOutState;
    procedure ApplySphinxLoginSettings;
  end;

var
  frmTestPage: TTestPageForm;

implementation

{$R *.dfm}

procedure TTestPageForm.ApplyLoggedInState;
begin
  lblStatus.Caption := 'Logged in. Use Logout to clear the Sphinx session (compare Sphinx 1 vs 2 behaviour).';
  btnLogout.Enabled := True;
  btnLoginAgain.Enabled := False;
end;

procedure TTestPageForm.ApplyLoggedOutState;
begin
  lblStatus.Caption := 'Logged out. Use Login again to start a new session.';
  btnLogout.Enabled := False;
  btnLoginAgain.Enabled := True;
end;

procedure TTestPageForm.ApplySphinxLoginSettings;
begin
  SphinxLogin1.RedirectUri := Dist_OAuthRedirectIndexHtml;
  SphinxLogin1.ClientId := App_Web_App_Id;
  SphinxLogin1.Scope := 'openid email';
  SphinxLogin1.Authority := Dist_BrowserAuthUrl;
end;

procedure TTestPageForm.btnLoginAgainClick(Sender: TObject);
begin
  SphinxLogin1.Login;
end;

procedure TTestPageForm.btnLogoutClick(Sender: TObject);
begin
  if SphinxLogin1.IsLoggedIn then
    SphinxLogin1.Logout;
  ApplyLoggedOutState;
end;

procedure TTestPageForm.SphinxLogin1UserLoggedIn(Args: TUserLoggedInArgs);
begin
  ApplyLoggedInState;
end;

procedure TTestPageForm.WebFormCreate(Sender: TObject);
begin
  lblStatus.Caption := 'Starting…';
  btnLogout.Enabled := False;
  btnLoginAgain.Enabled := False;
  ApplySphinxLoginSettings;
  try
    if not SphinxLogin1.IsLoggedIn then
      SphinxLogin1.Login
    else
      ApplyLoggedInState;
  except
    if SphinxLogin1.IsLoggedIn then
      SphinxLogin1.Logout;
    ApplyLoggedOutState;
  end;
end;

end.
