program webKGOrders;

uses
  Vcl.Forms,
  XData.Web.Connection,
  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},
  View.UserProfile in 'View.UserProfile.pas' {FViewUserProfile: TWebForm} {*.html},
  View.ErrorPage in 'View.ErrorPage.pas' {FViewErrorPage: TWebForm} {*.html},
  App.Config in 'App.Config.pas',
  Paginator.Plugins in 'Paginator.Plugins.pas',
  View.Items in 'View.Items.pas' {FViewItems: TWebForm} {*.html},
  View.Main in 'View.Main.pas' {FViewMain: TWebForm} {*.html},
  View.Home in 'View.Home.pas' {FViewHome: TWebForm} {*.html},
  View.Users in 'View.Users.pas' {FViewUsers: TWebForm} {*.html},
  View.EditUser in 'View.EditUser.pas' {FViewEditUser: TWebForm} {*.html},
  View.Orders in 'View.Orders.pas' {FViewOrders: TWebForm} {*.html},
  View.OrderEntryCorrugated in 'View.OrderEntryCorrugated.pas' {FOrderEntryCorrugated: TWebForm} {*.html},
  View.AddOrder in 'View.AddOrder.pas' {FAddOrder: TWebForm} {*.html},
  View.Search in 'View.Search.pas' {FSearch: TWebForm} {*.html},
  View.SetStatus in 'View.SetStatus.pas' {FSetStatus: TWebForm} {*.html},
  View.OrderEntryCuttingDie in 'View.OrderEntryCuttingDie.pas' {FOrderEntryCuttingDie: TWebForm} {*.html},
  View.OrderEntryWeb in 'View.OrderEntryWeb.pas' {FOrderEntryWeb: TWebForm} {*.html};

{$R *.res}

procedure DisplayLoginView(AMessage: string = ''); forward;

procedure DisplayMainView;

  procedure ConnectProc;
  begin
    if Assigned(FViewLogin) then
      FViewLogin.Free;
    TFViewMain.Display(@DisplayLoginView);
  end;

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

procedure DisplayLoginView(AMessage: string);
begin
  AuthService.Logout;
  DMConnection.ApiConnection.Connected := False;
  if Assigned(FViewMain) then
    FViewMain.Free;
  TFViewLogin.Display(@DisplayMainView, AMessage);
end;

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

procedure StartApplication;
begin
  if (not AuthService.Authenticated) or AuthService.TokenExpired then
    DisplayLoginView
  else
    DisplayMainView;
end;

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