unit View.Login;

interface

uses
  System.SysUtils, System.Classes, Web, WEBLib.Graphics, WEBLib.Controls, WEBLib.Forms, WEBLib.Dialogs,
  Vcl.Controls, Vcl.StdCtrls, WEBLib.StdCtrls, WEBLib.JSON,
  XData.Web.Client, WEBLib.ExtCtrls, Vcl.Imaging.pngimage,
  JS, XData.Web.Connection,
  App.Types, ConnectionModule;

type
  TFViewLogin = class(TWebForm)
    WebLabel1: TWebLabel;
    edtUsername: TWebEdit;
    edtPassword: TWebEdit;
    btnLogin: TWebButton;
    pnlMessage: TWebPanel;
    lblMessage: TWebLabel;
    btnCloseNotification: TWebButton;
    XDataWebClient: TXDataWebClient;
    WebImageControl1: TWebImageControl;
    lblClientVersion: TWebLabel;
    procedure btnLoginClick(Sender: TObject);
    procedure btnCloseNotificationClick(Sender: TObject);
    procedure WebFormShow(Sender: TObject);
  private
    FLoginProc: TSuccessProc;
    FMessage: string;
    procedure ShowNotification(Notification: string);
    procedure HideNotification;
  public
    class procedure Display(LoginProc: TSuccessProc); overload;
    class procedure Display(LoginProc: TSuccessProc; AMsg: string); overload;
  end;

var
  FViewLogin: TFViewLogin;

implementation

uses
  Auth.Service,
  View.ErrorPage;

{$R *.dfm}

procedure TFViewLogin.btnLoginClick(Sender: TObject);

  procedure LoginSuccess;
  begin
    FLoginProc;
  end;

  procedure LoginError(AMsg: string);
  begin
    ShowNotification('Login Error: ' + AMsg);
  end;
var
  hashPW: string;
begin
  AuthService.Login(
    edtUsername.Text, edtPassword.Text,
    @LoginSuccess,
    @LoginError
  );
end;

class procedure TFViewLogin.Display(LoginProc: TSuccessProc);
begin
  TFViewLogin.Display(LoginProc, '');
end;

class procedure TFViewLogin.Display(LoginProc: TSuccessProc; AMsg: string);

  procedure FormCreate(AForm: TObject);
  begin
    TFViewLogin(AForm).FMessage := AMsg;
  end;

begin
  if Assigned(FViewLogin) then
    FViewLogin.Free;
  FViewLogin := TFViewLogin.CreateNew(@FormCreate);
  FViewLogin.FLoginProc := LoginProc;
end;

procedure TFViewLogin.HideNotification;
begin
  pnlMessage.ElementHandle.classList.add('d-none');
  pnlMessage.Visible := False;
end;

procedure TFViewLogin.ShowNotification(Notification: string);
begin
  if Notification <> '' then
  begin
    lblMessage.Caption := Notification;
    pnlMessage.ElementHandle.classList.remove('d-none');
    pnlMessage.Visible := True;
  end;
end;

procedure TFViewLogin.btnCloseNotificationClick(Sender: TObject);
begin
  HideNotification;
end;

procedure TFViewLogin.WebFormShow(Sender: TObject);
begin
  FViewLogin.lblClientVersion.Caption := 'v' + DMConnection.clientVersion;
  if FMessage <> '' then
    ShowNotification(FMessage)
  else
    HideNotification;
end;


end.
