program emT3Web;

uses
  System.Classes,
  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';

{$R *.res}

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
    ShowAppDialog('' + AMsg);
  end;

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


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

  AuthService.Logout;
  DMConnection.ApiConnection.Connected := False;
  if Assigned(FViewMain) then
    FViewMain.Free;
  Login( userIdParam, taskIdParam, codeParam );
end;


procedure DoLogout(AMsg: string);
begin
  AuthService.Logout;
   ShowAppDialog('Logout successful ' + 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.

