#!/usr/bin/perl
# export-weekly-cal: Simple time summary tool wrapper around gcalcli
# Copyright 2013/11/29 Robin H. Johnson <robbat2@gentoo.org>
# gcalcli is from https://github.com/insanum/gcalcli
use Date::Parse qw(str2time);

sub duration {
	# This is a much simplified version of Time::Duration::duration
	my $raw = shift;
	my ($d,$h,$m,$s) = (0,0,0,0);
	#my $i = 86400; while($raw >= $i) { $d++; $raw-=$i; }
	my $i = 3600; while($raw >= $i) { $h++; $raw-=$i; }
	my $i = 60; while($raw >= $i) { $m++; $raw-=$i; }
	$s = $raw;
	return sprintf("%s%s%s%s",
		$d > 0 ? sprintf "%dd", $d : '',
		$h > 0 ? sprintf "%dh", $h : '',
		$m > 0 ? sprintf "%dm", $m : '',
		$s > 0 ? sprintf "%ds", $s : '',
	);

}

# TODO: This needs to be more flexible
my $arg_start=$ARGV[0];
my $arg_stop=$ARGV[1];
my $calname = 'Hours:SITKA:RJ';

my @cmd = ( 'gcalcli', '--24hr', '--nc', '--tsv', '--cal', $calname, 'agenda', $arg_start, $arg_stop );
open(my $fh, "-|", @cmd) || die "Can't open @cmd|: $!";
my ($duration_sum, $duration_week, $duration_day) = (0,0,0);
# TODO: Weekly subtotal not implemented
my ($last_date) = (undef);

while(<$fh>) {
	# TODO: Where is the location?
	my ($start_date, $start_time, $stop_date, $stop_time, $url, $desc) = split(/\t/);

	# TODO: Horrible summary hack
	if($start_date ne $last_date && defined($last_date)) {
		if($duration_day > 0) {
			printf "- Subtotal       %8.8s\n", duration($duration_day);
		}
		$duration_day = 0;
	}

	# Real time code
	# FIXME: This will cause bugs if an event overlaps the DST change.
	my $start = str2time(sprintf("%s %s UTC",$start_date,$start_time));
	my $stop = str2time(sprintf("%s %s UTC",$stop_date,$stop_time));
	my $duration = $stop-$start;
	$duration_sum += $duration;
	$duration_day += $duration;
	$duration = duration($duration);

	# Print it
	printf("%10s %5s %8.8s %s\n", $start_date, $start_time, $duration, $desc);

	# Ensure we detect day change
	$last_date = $start_date;
}
# Final summary
printf "= Total          %8.8s\n", duration($duration_sum);
