program emT3Web;

uses
  System.Classes,
  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.Test in 'View.Test.pas' {FTest: TWebForm} {*.html},
  View.TasksHTML in 'View.TasksHTML.pas' {FTasksHTML: TWebForm} {*.html},
  uNameManager in 'uNameManager.pas';

{$R *.res}

procedure DoLogout(AMsg: string = ''); forward;

procedure DisplayMainView;

  procedure ConnectProc;
  begin
    TFViewMain.Display(@DoLogout);
  end;

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


procedure Login(userId: string; taskId: string; urlCode: string);
  procedure LoginSuccess;
  begin
    DisplayMainView;
  end;

  procedure LoginError(AMsg: string);
  begin
    ShowMessage('Login Error: ' + AMsg);
  end;

begin
  AuthService.Login( userId, taskId, urlCode,
    @LoginSuccess,
    @LoginError
  );
end;


procedure DoLogin();
var
  userIdParam: string;
  taskIdParam: string;
  codeParam: string;
begin
  userIdParam := Application.Parameters.Values['user_id'];
  taskIdParam := Application.Parameters.Values['task_id'];
  codeParam := Application.Parameters.Values['url_code'];

  AuthService.Logout;
  DMConnection.ApiConnection.Connected := False;
  if Assigned(FViewMain) then
    FViewMain.Free;
  Login( userIdParam, taskIdParam, codeParam );
end;


procedure DoLogout(AMsg: string);
begin
  AuthService.Logout;
  ShowMessage('Logout successful: ' + AMsg);
end;


procedure UnauthorizedAccessProc(AMessage: string);
begin
  ShowMessage('UnauthorizedAccessProc: ' + AMessage);
end;


procedure StartApplication;
var
  ClientVer: string;
  dialogMsg: TStringList;
begin
  ClientVer := TDMConnection.clientVersion;
  DMConnection.InitApp(
    procedure
    begin
      DMConnection.SetClientConfig(
        procedure(Success: Boolean; ErrorMessage: string)
        begin
          if Success then
          begin
            DoLogin();
          end
          else
          begin
            asm
              var dlg = document.createElement("dialog");
              dlg.classList.add("shadow", "rounded", "border", "p-4");
              dlg.style.maxWidth = "500px";
              dlg.style.width = "90%";
              dlg.style.fontFamily = "system-ui, sans-serif";

              dlg.innerHTML =
                "<h5 class='fw-bold mb-3 text-danger'>emT3 web app</h5>" +
                "<p class='mb-3' style='white-space: pre-wrap;'>" + ErrorMessage + "</p>" +
                "<div class='text-end'>" +
                "<button id='refreshBtn' class='btn btn-primary'>Reload</button></div>";

              document.body.appendChild(dlg);
              dlg.showModal();

              document.getElementById("refreshBtn").addEventListener("click", function () {
                var base = location.origin + location.pathname;
                location.replace(base + "?ver=" + ClientVer + "&r=" + Date.now() + location.hash);
              });
            end;
          end;
        end);
    end,
    @UnauthorizedAccessProc
  );
end;


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

