package RiakSearch;

# https://wiki.basho.com/display/RIAK/Riak+Search

use strict;
use warnings;

use LWP::UserAgent;
use JSON::XS;
use Data::Dump qw/dump/;

sub new {
	my ($class, $url) = @_;

	my $ua = LWP::UserAgent->new;
	$ua->timeout(10);
	$ua->env_proxy;

	return bless {
		ua  => $ua,
		url => $url,
	}, $class;
}

sub request {
	my ($self, $method, $uri, $content, $headers) = @_;

	my $full_url = $self->{url} . "/riak/$uri";
	$full_url =~ s{//+}{/}g;
	$full_url =~ s{http:/}{http://};

	$headers->{'Content-Type'} = 'application/json' unless exists $headers->{'Content-Type'};

	my $req;

	if (defined $content) {
		$content = encode_json $content if ref $content;
		$req = HTTP::Request->new( $method, $full_url, undef, $content );
	} else {
		$req = HTTP::Request->new( $method, $full_url );
	}

	$req->header( $_ => $headers->{$_} ) foreach keys %$headers;
	$req->header( 'Host' => $1 ) if $self->{url} =~ m{http://([^/]+)};

	warn "# $method $full_url ", dump($req, $content);
	my $response = $self->{ua}->request($req);

	if ($response->is_success) {
		warn "$full_url ", $response->status_line,$/;
		return $response->content;
	} else {
		die($response->status_line . ":" . $response->content);
	}
}

1;
