program emT3web;

{$R *.dres}

uses
  Vcl.Forms,
  System.SysUtils,
  JS,
  Web,
  XData.Web.Connection,
  WEBLib.Dialogs,
  Auth.Service in 'Auth.Service.pas',
  App.Types in 'App.Types.pas',
  ConnectionModule in 'ConnectionModule.pas' {DMConnection: TWebDataModule},
  View.Login in 'View.Login.pas' {FViewLogin: TWebForm} {*.html},
  App.Config in 'App.Config.pas',
  View.Main in 'View.Main.pas' {FViewMain: TWebForm} {*.html},
  Utils in 'Utils.pas',
  View.TasksHTML in 'View.TasksHTML.pas' {FTasksHTML: TWebForm} {*.html},
  View.Home in 'View.Home.pas' {FHome: TWebForm} {*.html};

{$R *.res}

procedure DisplayAccessDeniedModal(const ErrorMessage: string);
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'>emT3web</h5>" +
      "<p class='mb-3' style='white-space: pre-wrap;'>" + ErrorMessage + "</p>" +
      "<div class='text-end'>" +
      "<button id='actionBtn' class='btn btn-primary'></button></div>";

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

    var btn = document.getElementById("actionBtn");

    if (
      (ErrorMessage.indexOf("Version mismatch") >= 0) ||
      (ErrorMessage.indexOf("old version") >= 0)
    ) {
      btn.textContent = "Reload";
      btn.addEventListener("click", function () {
        location.reload(true);
      });
    } else {
      btn.textContent = "Close";
      btn.addEventListener("click", function () {
        dlg.close();
        dlg.remove();
      });
    }
  end;
end;

procedure DisplayLoginView(AMessage: string = '');
begin
  AuthService.Logout;
  DMConnection.ApiConnection.Connected := False;

  if Assigned(FViewMain) then
    FViewMain.Free;

  if AMessage = '' then
    DisplayAccessDeniedModal('Access requires a valid emt3 link. Please reopen from emt3.')
  else
    DisplayAccessDeniedModal(AMessage);
end;

procedure DisplayMainView(const AUserId, ATaskId, ACode: string);
begin
  TFViewMain.Display(@DisplayLoginView, AUserId, ATaskId, ACode);
end;

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

procedure StartApplication;
var
  userIdParam: string;
  taskIdParam: string;
  codeParam: string;
begin
  userIdParam := Application.Parameters.Values['user_id'];
  taskIdParam := Application.Parameters.Values['task_id'];
  codeParam := Application.Parameters.Values['code'];

  DMConnection.SetClientConfig(
    procedure(Success: Boolean; ErrorMessage: string)
    begin
      if not Success then
      begin
        DisplayAccessDeniedModal(ErrorMessage);
        Exit;
      end;

      if AuthService.Authenticated and (not AuthService.TokenExpired) then
      begin
        DisplayMainView(userIdParam, taskIdParam, codeParam);
        Exit;
      end;

      if (userIdParam <> '') and (taskIdParam <> '') and (codeParam <> '') then
      begin
        AuthService.Login(
          userIdParam, taskIdParam, codeParam,
          procedure
          begin
            DisplayMainView(userIdParam, taskIdParam, codeParam);
          end,
          procedure(LoginError: string)
          begin
            DisplayLoginView('Invalid or expired link.' + sLineBreak + LoginError);
          end
        );
        Exit;
      end;

      DisplayLoginView;
    end
  );
end;

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