program emT3Web;

uses
  System.Classes,
  System.SysUtils,
  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.TaskItems in 'View.TaskItems.pas' {FTaskItems: TWebForm} {*.html},
  uNameOffCanvas in 'uNameOffCanvas.pas',
  uDropdownHelpers in 'uDropdownHelpers.pas',
  View.Login in 'View.Login.pas' {FViewLogin: TWebForm} {*.html},
  View.ErrorPage in 'View.ErrorPage.pas' {FViewErrorPage: TWebForm} {*.html},
  View.TimeEntries in 'View.TimeEntries.pas' {FTimeEntries: TWebForm} {*.html},
  uTaskPickerOffCanvas in 'uTaskPickerOffCanvas.pas';

{$R *.res}

procedure DisplayLoginView(AUserId: string = ''; ATaskId: string = ''; AMessage: string = ''); forward;
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
    if (Pos('401:', AMsg) = 1) or
       (Pos('Invalid url parameters', AMsg) > 0) or
       (Pos('Expired link', AMsg) > 0) then
      DisplayLoginView(userId, taskId)
    else
      ShowAppDialog('' + AMsg);
  end;

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


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


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

  if SameText(timeEntriesParam, 'true') then
  begin
    if AuthService.Authenticated and not AuthService.TokenExpired then
    begin
      DisplayMainView;
      Exit;
    end;

    DisplayLoginView('', '', '');
    Exit;
  end;

  userIdParam := Application.Parameters.Values['user_id'];
  taskIdParam := Application.Parameters.Values['task_id'];
  codeParam := Application.Parameters.Values['url_code'];

  if (userIdParam = '') or (taskIdParam = '') or (codeParam = '') then
  begin
    DisplayLoginView(userIdParam, taskIdParam);
  end
  else
  begin
    AuthService.Logout;
    DMConnection.ApiConnection.Connected := False;
    if Assigned(FViewMain) then
      FViewMain.Free;
    DMConnection.currentTaskId := taskIdParam;
    Login(userIdParam, taskIdParam, codeParam);
  end;
end;


procedure DoLogout(AMsg: string);
var
  userIdParam: string;
  taskIdParam: string;
  timeEntriesParam: string;
begin
  AuthService.Logout;

  timeEntriesParam := Application.Parameters.Values['time_entries'];

  if SameText(timeEntriesParam, 'true') then
  begin
    DisplayLoginView('', '', AMsg);
    Exit;
  end;

  userIdParam := Application.Parameters.Values['user_id'];
  taskIdParam := Application.Parameters.Values['task_id'];

  DisplayLoginView(userIdParam, taskIdParam, AMsg);
end;

procedure UnauthorizedAccessProc(AMessage: string);
begin
  ShowAppDialog('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
            ShowAppDialog(ErrorMessage, 'emT3 web app', True, 'Reload');
          end;
        end);
    end,
    @UnauthorizedAccessProc
  );
end;


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

