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

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

use CouchDB;
use Digest::MD5 qw(md5_hex);

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

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

my $db = CouchDB->new('10.60.0.95', 5984);
eval { $db->put("z_$UserID") }; # create user database

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};
	warn "# entry $entry ",dump($item);

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

	$item->{zapi_etag} = $item->{content}->{'zapi:etag'};

	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;

	my $old_item = $db->get( "z_$UserID/$id" );
	warn "# old_item ",dump($old_item);
	my $item_md5 = md5_hex encode_json $item;
	$item->{item_md5} = $item_md5;
	if ( $old_item->{zapi_etag} ne $item->{zapi_etag} || $item_md5 ne $old_item->{item_md5} ) {
		$item->{_rev} = $old_item->{_rev};
		$db->put( "z_$UserID/$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

	}

}
