program Delivery.Jobs.Reporter;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.IOUtils,
  System.SysUtils,
  JsonDataObjects,
  StompClient,
  Delivery.Jobs.Reporter.Pdf in 'Delivery.Jobs.Reporter.Pdf.pas',
  Delivery.Jobs.Reporter.Consts in 'Delivery.Jobs.Reporter.Consts.pas';

procedure Main;
begin

  if ParamCount < 1 then
    raise Exception.Create('Numero insufficiente di parametri');

  var LReportPath := ParamStr(1);

  if not TDirectory.Exists(LReportPath) then
    raise EDirectoryNotFoundException.Create('Directory di generazione report non esistente: ' + LReportPath);

  Sleep(15000);

  var LStompClient := StompUtils.StompClient
    .SetHost(MQ_HOST)
    .SetPort(MQ_PORT)
    .SetUserName(MQ_USERNAME)
    .SetPassword(MQ_PASSWORD)
    .Connect;

  LStompClient.Subscribe(Format('/queue/%s', [MQ_QUEUE_NAME]), TAckMode.amClient);

  while True do
  begin

    try

      var LStompFrame: IStompFrame;
      repeat
          LStompFrame := LStompClient.Receive(5000);
      until Assigned(LStompFrame);

      var LOrderData := LStompFrame.Body
        .Replace(sLineBreak, ' ');

      var LOrderJSON := TJsonObject.Parse(LOrderData) as TJsonObject;

      if LOrderJSON = nil then
      begin
        LStompClient.Nack(LStompFrame.MessageID);
        Continue;
      end;

      var LOrderPdfName := LOrderJSON['orderCode'] + '.pdf';
      var LOrderPdfPath := TPath.Combine(LReportPath, LOrderPdfName);

      TPdfWriter.WriteOrderTo(LOrderPdfPath, LOrderJSON);

      LStompClient.Ack(LStompFrame.MessageID);

    except on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
    end;

    Sleep(50);
  end;
end;

begin
  try
    Main;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
