program XDataMusicWeb;

{$R *.dres}

uses
  Vcl.Forms,
  XData.Web.Connection,
  View.Main in 'View.Main.pas' {FViewMain: TWebForm} {*.html},
  View.Home in 'View.Home.pas' {FViewHome: TWebForm} {*.html},
  View.Artist.Edit in 'View.Artist.Edit.pas' {FViewArtistEdit: TWebForm} {*.html},
  View.Artist.List in 'View.Artist.List.pas' {FViewArtistList: TWebForm} {*.html},
  View.Artist in 'View.Artist.pas' {FViewArtist: TWebForm} {*.html},
  Auth.Service in 'Auth.Service.pas',
  App.Types in 'App.Types.pas',
  ConnectionModule in 'ConnectionModule.pas' {DMConnection: TWebDataModule},
  View.Genre in 'View.Genre.pas' {FViewGenre: TWebForm} {*.html},
  View.Genre.List in 'View.Genre.List.pas' {FViewGenreList: TWebForm} {*.html},
  View.Genre.Edit in 'View.Genre.Edit.pas' {FViewGenreEdit: TWebForm} {*.html},
  View.Album in 'View.Album.pas' {FViewAlbum: TWebForm} {*.html},
  View.Album.List in 'View.Album.List.pas' {FViewAlbumList: TWebForm} {*.html},
  View.Album.Edit in 'View.Album.Edit.pas' {FViewAlbumEdit: TWebForm} {*.html},
  View.Track in 'View.Track.pas' {FViewTrack: TWebForm} {*.html},
  View.Track.List in 'View.Track.List.pas' {FViewTrackList: TWebForm} {*.html},
  View.Track.Edit in 'View.Track.Edit.pas' {FViewTrackEdit: TWebForm} {*.html},
  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',
  Grid.Plugins in 'Grid.Plugins.pas',
  Dataset.Plugins in 'Dataset.Plugins.pas',
  Grid.Settings in 'Grid.Settings.pas',
  Paginator.Plugins in 'Paginator.Plugins.pas';

{$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);
  Application.Run;
  DMConnection.InitApp(@StartApplication, @UnauthorizedAccessProc);
end.
