package WebPAC::Output::Riak;

use warnings;
use strict;

use base qw/WebPAC::Common WebPAC::Output Class::Accessor/;
__PACKAGE__->mk_accessors(qw(
	input
	url
	database
	bucket
));

use Data::Dump qw/dump/;
use URI;
use Net::Riak;

=head1 NAME

WebPAC::Output::Riak - feed data into Riak Search

=head1 FUNCTIONS

=head2 init

  $out->init;

=cut

sub init {
	my $self = shift;
	my $log = $self->_get_logger;

	$log->debug('init');

	my $bucket = $self->bucket || join('.', $self->database, $self->input || 'webpac2' );

	$self->{_riak} = Net::Riak->new( host => $self->url );
	$self->{_bucket} = $self->{_riak}->bucket( $bucket );
	$self->{_bucket}->set_properties({
		precommit => [ { mod => 'riak_search_kv_hook', fun => 'precommit' } ],
	});

	$log->info( $self->url,"/riak/$bucket" );
#	warn dump($self->{_bucket}->get_properties);

	$self->{_count} = 0;

	return 1;
}


=head2 add

Adds one entry to database.

  $out->add( 42, $ds );

=cut

sub add {
	my ($self,$id,$ds) = @_;
	my $log = $self->_get_logger;

#	$log->debug( 'ds = ', $id, sub { dump($ds) } );

	my $data;
	$data->{$_} = join(' ', @{ $ds->{$_}->{search} }) foreach
		map { m/^\d+$/ ? $_ = $_ . '_num' : $_ }
		# add _num suffix for riak search https://wiki.basho.com/display/RIAK/Riak+Search+-+Schema
		grep { exists $ds->{$_}->{search} }
		keys %$ds;

	my $obj = $self->{_bucket}->new_object( $id, $data );
	$obj->store;

	$log->debug( 'json = ', $id, sub { dump($data) } );

	$self->{_count}++;

	return 1;
}

=head2 finish

 $out->finish;

=cut

sub finish {
	my $self = shift;

	my $log = $self->_get_logger();

	$log->info('finish ', $self->{_count}, ' documents');

	1;
}

=head1 AUTHOR

Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>

=head1 COPYRIGHT & LICENSE

Copyright 2010 Dobrica Pavlinusic, All Rights Reserved.

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

=cut

1; # End of WebPAC::Output::Riak
