program testEventosMultiSignal;

{$APPTYPE CONSOLE}

uses
{$IFDEF WIN32}
  ipcthrd in '..\..\src_libnettopos\fctopos\IPC\Win32\ipcthrd.pas',
  windows,
{$ELSE}
  timeLib in '..\..\src_libnettopos\fctopos\timeLib.pas',
  uemuladorwinipc in '..\..\src_libnettopos\fctopos\IPC\Linux\uemuladorwinipc.pas',
  usemaforopolenta in '..\..\src_libnettopos\fctopos\IPC\Linux\usemaforopolenta.pas',
  ipcobjs in '..\..\src_libnettopos\fctopos\IPC\Linux\ipcobjs.pas',
  uKeyDir in '..\..\src_libnettopos\libnettopos\uKeyDir.pas',
  baseunix,
{$ENDIF}
  SysUtils;

var
  nSenializaciones, iSenial, timeOutMS: Integer;
  nomEv: String;
{$IFDEF WIN32}
  evento: TEvent;
{$ELSE}
  eventoEspera: TEventRX;
  eventoSenial: TEventTX;
{$ENDIF}

procedure crearArchiKey;
{$IFNDEF WIN32}
var
  f: TextFile;
  path: String;
{$ENDIF}
begin
{$IFNDEF WIN32}
  nomEv:= fpgetenv('HOME') + '/archikeys/keyTestEventosMultiSignal';
  if not FileExists(nomEv) then
  begin
    path:= ExtractFilePath(nomEv);
    if not DirectoryExists(path) then
      ForceDirectories(path);
    AssignFile( f, nomEv );
    Rewrite( f );
    writeln( f, 'ArchiKey: ', nomEv, ' - no borrar.' );
    closefile( f );
  end;
{$ELSE}
  nomEv:= 'keyTestEventosMultiSignal';
{$ENDIF}
end;

procedure showHelp;
begin
  writeln('Uso:');
  writeln('testEventosMultiSignal (s)enializar');
  writeln('testEventosMultiSignal (e)sperar nSenializaciones timeOutMS');
  writeln;
end;

begin
  crearArchiKey;
  if ParamCount = 1 then
  begin
    if AnsiLowerCase(ParamStr(1)) = 's' then
    begin
{$IFDEF WIN32}
      evento:= TEvent.Create(nomEv, false);
      evento.Signal;
      evento.Free;
{$ELSE}
      eventoSenial:= TEventTX.Create(nomEv, 1);
      eventoSenial.Signal;
      eventoSenial.Free;
{$ENDIF}
    end
    else
      showHelp;
  end
  else if ParamCount = 3 then
  begin
    if AnsiLowerCase(ParamStr(1)) = 'e' then
    begin
      try
        nSenializaciones:= StrToInt(ParamStr(2));
        timeOutMS:= StrToInt(ParamStr(3));
{$IFDEF WIN32}
        evento:= TEvent.Create(nomEv, false);
{$ELSE}
        eventoEspera:= TEventRX.Create(nomEv, 1);
{$ENDIF}

        for iSenial:= 1 to nSenializaciones do
        begin
{$IFDEF WIN32}
          if not evento.Wait(timeOutMS) then
{$ELSE}
          if not eventoEspera.Wait(timeOutMS) then
{$ENDIF}
            Writeln('No me despertaron del evento en ', timeOutMS, 'ms. iSenial= ', iSenial, ', nSenializaciones= ', nSenializaciones)
          else
            Writeln('Me despertaron del evento. iSenial= ', iSenial, ', nSenializaciones= ', nSenializaciones);
        end;

{$IFDEF WIN32}
        evento.Free;
{$ELSE}
        eventoEspera.Free;
{$ENDIF}
      Except
        showHelp;
      end;
    end
    else
      showHelp;
  end
  else
    showHelp;
end.
