#!/usr/bin/perl

# http://wiki.apache.org/couchdb/HTTP_database_API#Changes

use warnings;
use strict;

use LWP::UserAgent;
use Data::Dump qw(dump);
use JSON::XS;

my $ua = LWP::UserAgent->new;
$ua->timeout( 15 ); # re-cycle request every hour
$ua->env_proxy;

my $seqnum = 0;
our $last_rev = '';

while(1) {


my $response = $ua->get(
	'http://localhost:5984/monitor/_changes?feed=continuous;include_docs=true;since='.$seqnum
	, ':content_cb' => sub {
		my ( $data, $response, $protocol ) = @_;
		my $json = decode_json $data;
		my $rev = $json->{changes}->[0]->{rev} || warn "no rev";
		if ( $last_rev eq $rev ) {
			warn "duplicate $last_rev\n";
		} else {
			$last_rev = $rev;
			warn "# $rev ",dump( $json );
			$seqnum = $json->{last_seq} if exists $json->{last_seq};
		}
	}
);

if ($response->is_success) {
	print "seqnum: $seqnum";
}
else {
	die $response->status_line;
}


}#while
