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,
  JS, XData.Web.Connection, WEBLib.ExtCtrls,
  App.Types, ConnectionModule, XData.Web.Client, Vcl.Imaging.pngimage;

type
  TFViewLogin = class(TWebForm)
    WebLabel1: TWebLabel;
    edtUsername: TWebEdit;
    edtPassword: TWebEdit;
    btnLogin: TWebButton;
    pnlMessage: TWebPanel;
    lblMessage: TWebLabel;
    btnCloseNotification: TWebButton;
    XDataWebClient: TXDataWebClient;
    WebImageControl1: TWebImageControl;
    procedure btnLoginClick(Sender: TObject);
    procedure btnCloseNotificationClick(Sender: TObject);
    procedure WebFormCreate(Sender: TObject);
  private
    FLoginProc: TSuccessProc;
    FMessage: string;
    procedure ShowNotification(Notification: string);
    procedure HideNotification;
    [async] procedure VerifyVersion();
  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;

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.hidden := True;
end;

procedure TFViewLogin.ShowNotification(Notification: string);
begin
  if Notification <> '' then
  begin
    lblMessage.Caption := Notification;
    pnlMessage.ElementHandle.hidden := False;
  end;
end;

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

procedure TFViewLogin.VerifyVersion();
var
  xdcResponse: TXDataClientResponse;
begin
  xdcResponse := await(XDataWebClient.RawInvokeAsync('IAuthService.VerifyVersion',
        ['1.0.0']));
  ShowNotification(string(TJSObject(xdcResponse.Result)['value']));
end;

procedure TFViewLogin.WebFormCreate(Sender: TObject);
begin
//  lblAppTitle.Caption := 'EM Systems - webCharms App ver 0.9.2.22';
  VerifyVersion();
  if FMessage <> '' then
    ShowNotification(FMessage)
  else
    HideNotification;
end;

end.
