#!/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;
my $ticket;

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

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

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

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

		foreach my $tag ( @{ $json->{tags} } ) {
			$tag = $tag->{tag};
			warn "# tag $id $tag\n";
			next unless $tag =~ m/#(\d+)/;
			push @{ $ticket->{$1} }, $id;
		}
	}


}

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

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