#!/usr/bin/perl -w

use strict;
use warnings;

my $filename = shift;

open(my $fh, '<:encoding(UTF-8)', $filename)
    or die "Could not open file '$filename' $!";

my @request_entries;
my $is_request_entry = 0;

while (my $row = <$fh>) {
  chomp $row;

  if ($row =~ m/\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d.\d\d\d (\d+) \[(\d+)\] Request: \*+/) {
    my $pid1 = $1;
    my $pid2 = $2;
    push @request_entries, { pid1 => $pid1, pid2 => $pid2, request => '', routing => '', time => -1 };
    $is_request_entry = 1;

  } elsif ($row =~ m/\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d.\d\d\d (\d+) \[(\d+)\] time: (\d+.\d+)/) {
    my $pid1 = $1;
    my $pid2 = $2;
    my $time = $3;

    $is_request_entry = 0;

    my $found = -1;
    foreach my $i (reverse 0..$#request_entries) {
      if ($request_entries[$i]->{pid1} == $pid1 && $request_entries[$i]->{pid2} == $pid2) {
        $found = $i;
        last;
      }
    }
    if ($found != -1) {
      $request_entries[$found]->{time} = $time;
    }

  } elsif ($row =~ m/\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d.\d\d\d (\d+) \[(\d+)\]/) {
    $is_request_entry = 0;

  } elsif (!!$is_request_entry) {
    $request_entries[-1]->{request} = $row         if $is_request_entry == 1;
    $request_entries[-1]->{routing} = $row         if $is_request_entry == 2;
    $request_entries[-1]->{params} .= $row . "\n"  if $is_request_entry > 4; # 3 is empty, 4 is word "Params"
    $is_request_entry++;

  } else {
    print "unknown line: $row\n";
  }
}

# sort by timne
@request_entries = sort { $a->{time} <=> $b->{time} } @request_entries;

foreach my $r (@request_entries) {
  if ($r->{routing} =~ m/action: add_item/) {
    #print $r->{request} . "\n";
    #print $r->{routing} . "\n";
    print $r->{time} . "\n";
    #print $r->{params} . "\n";
    #print "\n";
  }
}

