#!/usr/bin/perl

use Image::EXIF;
use RDF::Simple::Serialiser;
use Time::Piece;
use Geo::Track::Log;
use strict;
use warnings;

die "Usage: $0 <offset> <base href> <track.gpx> <maker\@email.com> <files.jpg> ...\nOffset can take the form [+-]3h2m1s etc.\n\n"
	unless @ARGV >= 5;

my $offset = parse_duration(shift);
my $base  = shift;
my $gpx_track = shift;
my $maker_email = shift;
my @files = map(glob, @ARGV);

my $s = RDF::Simple::Serialiser->new;
$s->ns->lookup('locative' => 'http://locative.net/2004/packet#');

my $log = Geo::Track::Log->new;
$log->loadTrackFromGPX($gpx_track);

my @rdf = ();
my $person_id = $s->genid;

push @rdf, [$person_id,'rdf:type','foaf:Person'];
push @rdf, [$person_id, 'foaf:mbox', 'mailto:'.$maker_email];
push @rdf, geoloc_images(\@files, $log, $offset); 
print $s->serialise(@rdf);

sub geoloc_images {
	my ($images,$log,$offset) = @_;
	my $exif = Image::EXIF->new;
	my @triples;

	foreach my $img (@$images) {
		$exif->file_name($img);
		my $i = $exif->get_image_info() or next;
		my $created = $i->{'Image Created'} or next;

# exif date format looks like '2004:08:28 08:34:45'

		my $t = Time::Piece->strptime($created, "%Y:%m:%d %H:%M:%S");

# add time offset to time here, if applicable.
		$t = $t + $offset if $offset;		
		my $logtime = $t->strftime("%Y-%m-%d %H:%M:%S");
		# worry about UTC or timezone specification?	
		my $icaltime = $t->strftime("%Y%m%dT%H%M%S");
		my ($approx,$previous,$next) = $log->whereWasI($logtime);

		my $pkt = $s->genid;
		$img =~ s/^\/?/$base/os;
		push @triples, [$img,'ical:datetime',$icaltime];
		push @triples, [$img,'foaf:maker',$person_id];
		push @triples, [$pkt,'locative:media',$img];
		push @triples, [$pkt,'geo:lat',$approx->{lat}];
		push @triples, [$pkt,'geo:long',$approx->{long}];
		push @triples, [$pkt,'rdf:type','locative:Packet'];		

		if ((my $thumb = $img) =~ s/-l.jpg/-s.jpg/ios) {
		    push @triples, [$img,'foaf:thumbnail',$thumb];
		}
	}
	return @triples;
}	

sub parse_duration {
    my $duration = shift;
    my %units = ( d => 86400, h => 3600, m => 60, s => 1 );
    my $sum = 0;
    while ($duration =~ s/(\d+)([dhms])//ios) {
	$sum += $1 * $units{lc $2};	
    }	
    $sum += $1 if $duration =~ /(\d+)/os;
    $sum = -$sum if $duration =~ /-/os;
    return $sum;
}

