#!/usr/bin/perl
# This script parses files generated by timelog.pl
use strict;
use POSIX qw(strftime);
use List::Util qw(any);
#use GD;

my %matchgroups = (
	browser => "(.*Chromium|rekonq)",
	terminal => "QTerminal",
	editor => ".*SciTE",
	mail => "(.*Thunderbird|^Write: |^Sending Message|^Attach File)",
	pdf => ".*Okular",
	ide => "(.*Qt Creator|CMake Wizard)",
	qgerbil => "(^Gerbil - |Open Descriptor or Image File)",
	chat => "(^Quassel IRC|.*Skypeâ„¢.*)",
	geeqie => ".*Geeqie",
	diff => ".*Meld",
	office => "(abiword|^LibreOffice|.*- LibreOffice.*|.*Gnumeric)",
	dtp => "^Scribus",
	win => "^rdesktop",
	gimp => "(.*GIMP|GNU Image Manipulation Program)",
	dialog => "(Open File|Open|Saved Files|Import|Export|Pick a Font|Options|Save As|New|New Document|Warning|Confirm)"
);

sub secfmt {
	sprintf "%2dd %02d:%02d:%02d",(gmtime shift)[7,2,1,0];
#	strftime("%T", gmtime(shift));
}

my ($file, $filter) = @ARGV;
open my $log, $file or die "Could not open $file: $!\n";

my $laststamp = -1;
my @oldentry;
my %actsum;
my %acttagsum;
my %acttagtitlesum;
my %titlesum;
my $inactivesum = 0;
my $total = 0;

my @entry;
while (<$log>)  {
	chomp;
	next if /^spurious/;
	@entry = split /\t/;
	if (@oldentry) {
		my ($date, $time, $stamp, $act, $tag, $title) = @oldentry;
		my $spent = @entry[2] - $stamp;

		next if ($filter and not ($date =~ /$filter/));

		$total += $spent;
		if ($act eq 'inactive') {
			$inactivesum += $spent;
			next;
		}
		# ignore incomplete states
		next if (any {$_ eq '0'} ($act, $tag, $title));

		while (my ($name, $regex) = each %matchgroups)
		{
			$title = $name if $title =~ /$regex/;
		}
		my $at = "$act,,,$tag";
		my $att = "$at,,,$title";
		for ($actsum{$act}, $acttagsum{$at}, $acttagtitlesum{$att}, $titlesum{$title}) {
			$_ = ($_ + $spent);
		}
	}
} continue {
	@oldentry = @entry;
}

print "============================ Activities ============================\n";
foreach my $act (sort { $actsum{$b} <=> $actsum{$a} } keys %actsum) {
	printf "%s %s\n", secfmt($actsum{$act}), $act;

	my @tagkeys = sort { $acttagsum{$b} <=> $acttagsum{$a} } grep { /^$act/ } keys %acttagsum;
	foreach my $at (@tagkeys) {
		printf "\t%s %s\n", secfmt($acttagsum{$at}), (split /,,,/, $at, 2)[1];
		my @ttkeys = sort { $acttagtitlesum{$b} <=> $acttagtitlesum{$a} } grep { /^$at/ } keys %acttagtitlesum;
		foreach my $att (@ttkeys) {
			last if ($acttagtitlesum{$att} < 10); # don't report peanuts
			printf "\t\t%s %s\n", secfmt($acttagtitlesum{$att}), (split /,,,/, $att, 3)[2];
		}
	}
}

print "=========================== Applications ===========================\n";
foreach my $title (sort { $titlesum{$b} <=> $titlesum{$a} } keys %titlesum) {
	last if ($titlesum{$title} < 10); # don't report peanuts
	printf "%s %s\n", secfmt($titlesum{$title}), $title;
}

print "============================= General ==============================\n";
printf "%s %s\n", secfmt($inactivesum), "inactive";
printf "%s %s\n", secfmt($total), "recorded in total";

