#!/usr/bin/perl

use lib 'lib';
use utf8;
use strict;
use CGI qw(:standard);
use RDF::MicroTurtle;
use Data::Dumper;

if (param('acct') =~ m'/' || !length param('acct'))
{
	print header("text/plain; charset=utf-8");
	print <<EOF;
This service takes three parameters:

	acct   = An identi.ca account name (e.g. 'tobyink')
	notice = An identi.ca notice number which must have been posted
	         by that account. (optional)
	format = Preferred Internet Content-Type for response. (optional)

EOF
	exit;
}

my $ttldent = RDF::MicroTurtle->new_from_feed( identica_account => 'http://identi.ca/' . param('acct') );
my $fmt = lc(param('format'));
$fmt =~ s/ /\+/g;

unless ($fmt)
{
	my @accepts = (
		['text/plain', Accept('text/plain')] ,
		['text/n3', Accept('text/n3')] ,
		['text/rdf+n3', Accept('text/rdf+n3')] ,
		['application/rdf+xml', Accept('application/rdf+xml')] ,
		['application/rss+xml', Accept('application/rss+xml')] ,
		['application/turtle', Accept('application/turtle')] ,
		['text/turtle', Accept('text/turtle')] ,
		['application/x-turtle', Accept('application/x-turtle')] ,
		['text/vnd.graphviz', Accept('text/vnd.graphviz')] ,
	);
	my @sorted = sort 
		{ ($a->[1]!=$b->[1]) ? ($b->[1] <=> $a->[1]) : ($a->[0] cmp $b->[0]) }
		@accepts;
	$fmt = $sorted[0]->[0];
}

my %redland = (
	'text/plain'           => 'ntriples',
	'text/n3'              => 'turtle',
	'text/rdf+n3'          => 'turtle',
	'application/rdf+xml'  => 'rdfxml-abbrev',
	'application/rss+xml'  => 'rss-1.0',
	'application/turtle'   => 'turtle',
	'text/turtle'          => 'turtle',
	'application/x-turtle' => 'turtle',
	'text/vnd.graphviz'    => 'dot',
);

if (defined $redland{$fmt})
{
	print header("$fmt; charset=utf-8");
}
else
{
	print header("text/plain; charset=utf-8");
	print <<EOF;
Unrecognised format '$fmt'.

Recognised formats are:

	text/n3
	text/plain
	text/vnd.graphviz
	application/rdf+xml
	application/rss+xml
	application/turtle
EOF
	exit;
}

if (param('notice') =~ /^[0-9]+$/)
{
	print $ttldent->to_string($redland{$fmt}, 'http://identi.ca/notice/'.param('notice'));
}
else
{
	print $ttldent->to_string($redland{$fmt}, $ttldent->{'arguments'}->{'feed_uri'});
}
