#!/usr/bin/perl -w

my $path = $ENV{'HOME'} . "/timelog/";
my $logicalday = '4 hours ago';
my %times = ();

if (@ARGV == 0) {
  my $now = `gdate -d '$logicalday' +%Y.%m.%d`;
  doday($now, 1);
  dooutput();
} elsif ($ARGV[0] eq "week") {
  my $dow = `gdate -d '$logicalday' +%w`; chomp($dow);
  for (my $i = 0; $i <= $dow; $i++) {
    my $ago = $dow - $i;
    my $day = `gdate -d '$ago days ago $logicalday' +%Y.%m.%d`; chomp($day);
    if ($ago > 0) {
      doday($day, 0);
    } else {
      doday($day, 1);
    }
  }
  dooutput();
} elsif ($ARGV[0] eq "lastweek") {
  my $dow = `gdate -d '$logicalday' +%w`; chomp($dow);
  for (my $i = 7; $i > 0; $i--) {
    my $ago = $i + $dow;
    my $day = `gdate -d '$ago days ago $logicalday' +%Y.%m.%d`; chomp($day);
    doday($day, 0);
  }
  dooutput();
}


sub doday {
  my ($date, $istoday) = @_; chomp($date);
  open(my $file, "<", $path . $date) or return;

  my ($start, $current);
  foreach (<$file>) {
    my $line = $_; chomp($line);
    $line =~ /^([0-9]+) (.+)$/ or next;
    my ($time, $event) = ($1, $2);
    defined($start) and defined($current) and do {
      defined($times{$current}) or $times{$current} = 0;
      $times{$current} += $time - $start;
    };
    $start = $time;
    $current = $event;
  }
  $istoday and defined($start) and defined($current) and do {
    my $time = `gdate +%s`; chomp($time);
    defined($times{$current}) or $times{$current} = 0;
    $times{$current} += $time - $start;
  };
}

sub dooutput {
  foreach(sort(keys %times)) {
    printf "%-15s %5.1f h\n", $_, $times{$_} / 3600.0;
  }
}
