#!/usr/bin/perl
use warnings;
use strict;

use LWP::Simple;
use XML::Simple;
use JSON;
use Data::Dump qw(dump);

my $UserID = $ENV{UserID} || die "usage: UserID=1234 key=abcd $0";
my $key    = $ENV{key}    || die "key required";

my $FETCH  = $ENV{FETCH}  || 0;

my $url = "https://api.zotero.org/users/$UserID/items?key=$key&format=atom&content=json&order=dateModified&sort=desc";

my $file = "$UserID.atom";

warn "# $url\n";
if ( $FETCH && mirror( $url => $file ) == RC_NOT_MODIFIED ) {
	warn "not modified";
#	exit 0;
}

my $feed = XMLin( $file );
#warn "# feed ",dump($feed);

my $tree;

foreach my $entry ( keys %{ $feed->{entry} } ) {
	warn "ENTRY $entry\n";
	my $id = $entry;
	$id =~ s{.+/items/}{}; # leave just ID

	my $e = $feed->{entry}->{$entry};

	foreach my $link ( @{ $e->{link} } ) {
		warn "# link ",dump($link);
		if ( $link->{rel} eq 'up' ) {
			my $up = $link->{href};
			$up =~ s{.+/items/}{};
			$up =~ s{\?.+}{};
			push @{ $tree->{$up} }, $id;
		}
	}

	if ( $e->{content}->{'zapi:type'} eq 'json' ) {
		my $json = $e->{content}->{content};
		warn "# $json\n";
		$e->{json} = decode_json $json;
		warn ">> $id ", dump $e->{json};
	}	


}

warn "# tree ",dump( $tree );
