program emSystemsWebsite;

{$R *.dres}

uses
  Vcl.Forms,
  WEBLib.Forms,
  View.Home in 'View.Home.pas' {FHome: TWebForm} {*.html},
  View.PublicSafety in 'View.PublicSafety.pas' {FPublicSafety: TWebForm} {*.html},
  View.RecordsManagement in 'View.RecordsManagement.pas' {FRecordsManagement: TWebForm} {*.html},
  View.CustomSoftware in 'View.CustomSoftware.pas' {FCustomSoftware: TWebForm} {*.html},
  View.AboutUs in 'View.AboutUs.pas' {FAboutUs: TWebForm} {*.html},
  View.ContactUs in 'View.ContactUs.pas' {FContactUs: TWebForm} {*.html},
  Utils in 'Utils.pas',
  ConnectionModule in 'ConnectionModule.pas' {DMConnection: TWebDataModule};

{$R *.res}

procedure ShowVersionModal(const errorMessage, clientVer: string);
begin
  asm
    var dlg = document.createElement("dialog");
    dlg.classList.add("shadow", "rounded", "border", "p-4");
    dlg.style.maxWidth = "520px";
    dlg.style.width = "92%";
    dlg.style.fontFamily = "system-ui, sans-serif";

    dlg.innerHTML =
      "<h5 class='fw-bold mb-3 text-danger'>EM Systems web site</h5>" +
      "<p class='mb-3' style='white-space: pre-wrap;'>" + errorMessage + "</p>" +
      "<div class='text-end'>" +
      "<button id='refreshBtn' class='btn btn-danger'>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;

procedure StartRouting;
begin
  asm
    window.addEventListener('hashchange', function() {
      window.scrollTo(0, 0);
    }, false);

    if (window.location.hash === '') {
      window.location.hash = '#FHome';
    }
  end;

  if not Application.Route then
    Application.CreateForm(TFHome, FHome);
  end;

procedure StartApplication;
var
  clientVer: string;
begin
  clientVer := TDMConnection.clientVersion;

  DMConnection.InitApp(
    procedure
    begin
      DMConnection.SetClientConfig(
        procedure(success: Boolean; errorMessage: string)
        begin
          if success then
            StartRouting
          else
            ShowVersionModal(errorMessage, clientVer);
        end
      );
    end
  );
end;

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

