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

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

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_items;

my $items;

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->{content} = 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_items->{$1} }, $id;
		}
	}

	$items->{$id} = $item;

}

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

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


my $rt = RT::Client::REST->new(
	server => 'http://rt.rot13.org/rt',
	timeout => 30,
);

$rt->login(username => $ENV{RT_USER}, password => $ENV{RT_PASSWORD});

foreach my $nr ( keys %$ticket_items ) {

	my $ticket = $rt->show(type => 'ticket', id => $nr);
	warn "# ticket $nr ",dump($ticket);

	if ( $ticket->{Queue} !~ m/ILL/i ) {
		warn "SKIP $ticket not in ILL queue!";
		next;
	}

	foreach my $id ( @{ $ticket_items->{$nr} } ) {
		warn "# item $id ",dump( $items->{$id} );

		$rt->comment( ticket_id => $nr, message => dump( $items->{$id} ) );

		last; # FIXME just first

	}

}
