#!/usr/bin/perl -w
#
# Statistics program to accompany focus-tracker.jl
# Adam Spiers <adam@spiers.net>
#
# See homepage for focus-tracker.jl and latest version:
# http://adamspiers.org/computing/sawfish/
#
# $Id$
#

use strict;
use Date::Calc qw(Day_of_Week);

my %r = ();

my $log = "$ENV{HOME}/.sawfish/focus.log";
parse_log($log);
header();
cat_totals();
print "\n";
cat_day_totals();

exit 0;

##############################################################################

sub parse_log {
  my $log = shift;
  open(LOG, $log) or die "Couldn't open $log: $!\n";

  my (%last, %this) = ();
  while (<LOG>) {
    @this{qw/date secs ws name class/}
      = m!^(\d\d/\d\d/\d{4}) +(\d+): ws\{(.*?)} name\{(.*?)} class\{(.*)}!;

    next unless $last{secs};

    if ($this{date} eq $last{date}) {
      my $duration = $this{secs} - $last{secs};
      tot_up($this{date}, $this{name}, $duration);
    }
  }
  continue {
    %last = %this;
  }
    
  close(LOG);

  my $secs = time % (3600 * 24);
  tot_up($last{date}, $last{name}, $secs - $last{secs});
}

sub tot_up {
  my ($date, $cat, $duration) = @_;

  # could munge $cat here

  # day, category
  $r{day_cat}{$date}{$cat} += $duration;

  # day, total
  $r{day_total}{$date}++;

  # total, category
  $r{cat}{$cat} += $duration;

  # total, total
  $r{total} += $duration;
}

sub header {
  my $size = -s $log;
  print <<EOF;
Logfile: $log
Size: $size bytes
Total duration: @{[ duration_string($r{total}) ]}
=========================================================================

EOF
}

sub cat_totals {
  print <<EOF;
Category totals
---------------

EOF

  foreach my $cat (sort { $r{cat}{$b} <=> $r{cat}{$a} } keys %{$r{cat}}) {
    print " " . duration_string($r{cat}{$cat}) . "  $cat\n";
  }
}

sub cat_day_totals {
  print <<EOF;
Category totals by day
----------------------
  
EOF

  foreach my $day (sort keys %{$r{day_cat}}) {
    print " $day\n";
    foreach my $cat (sort { $r{day_cat}{$day}{$b} <=> $r{day_cat}{$day}{$a} }
                          keys %{$r{day_cat}{$day}})
    {
      print "   " . duration_string($r{day_cat}{$day}{$cat}) . "  $cat\n";
    }
    my $total = duration_string($r{day_total}{$day});
    print <<EOF;
   ------------------------------------------------------------------
   $total  total

EOF
  }
}

sub duration_string {
  my $secs  = shift;

  my $days  = int($secs / (3600 * 24));
  $secs     = $secs % (3600 * 24);

  my $hours = int($secs / 3600);
  $secs     = $secs % 3600;

  my $mins  = int($secs / 60);
  $secs     = $secs % 60;

  my $out = '';

  if (1) {
    $out = sprintf "%3d:%02d:%02d:%02d", $days, $hours, $mins, $secs;
  }
  else {
    $out .= sprintf "%3d day%s",   $days,  ($days  > 1) ? 's' : '' if $days;
    $out .= sprintf " %2d hour%s", $hours, ($hours > 1) ? 's' : '' if $hours;
    $out .= sprintf " %2d min%s",  $mins,  ($mins  > 1) ? 's' : '' if $mins;
    $out .= sprintf " %2d sec%s",  $secs,  ($secs  > 1) ? 's' : '' if $secs;
  }

  return $out;
}
