package WWW::ManageWP::Remote;
use strict;
use warnings;
use base 'WWW::ManageWP';
use URI::Escape;
use HTTP::Tiny;
use JSON;

##########
## Init ##
##########

sub new {
	my $self               = shift->SUPER::new(@_);
	$self->{_http_handler} = HTTP::Tiny->new();
	$self->{_json_handler} = JSON->new->utf8();
	return $self;
}

##########
## Core ##
##########

sub delete {
	my $self   = shift;
	my $params = $self->_prep_args([qw/method/], @_);
	my $url    = $self->_build_url(method => $params->{method})
		. $self->_build_get_params($params->{request_params});
	return $self->_handle_response($self->http->delete($url));
}

sub get {
	my $self   = shift;
	my $params = $self->_prep_args([qw/method/], @_);
	my $url    = $self->_build_url(method => $params->{method})
		. $self->_build_get_params($params->{request_params});
	return $self->_handle_response($self->http->get($url));
}

sub post {
	my $self   = shift;
	my $params = $self->_prep_args([qw/method request_params/], @_);
	my $url    = $self->_build_url(method => $params->{method});
	return $self->_handle_response(
		$self->http->post_form($url, $params->{request_params}),
	);
}

##########
## Help ##
##########

sub http {return shift->{_http_handler}}
sub json {return shift->{_json_handler}}

#############
## Private ##
#############

sub _build_get_params {
	my $self   = shift;
	my $params = shift;
	my $get_params;
	while (my ($key, $val) = each(%{$params})) {
		my $safe_key = uri_escape($key);
		my $safe_val = uri_escape($val);
		$get_params .= "&$safe_key=$safe_val";
	}
	return $get_params || '';
}

sub _build_url {
	my $self   = shift;
	my $params = $self->_prep_args([qw/method/], @_);
	my $key    = $self->apiKEY;
	my $url    = $self->apiURL;
	if (!($url =~ m/\/$/)) {
		$url .= '/';
	}
	return "${url}$params->{method}?api_key=${key}";
}

sub _handle_response {
	my $self     = shift;
	my $response = shift;
	if ($response->{status} == 200 && $response->{success} == 1) {
		my $content = $self->json->decode($response->{content});
		return $self->_handle_response_success($content);
	}
	my $status  = $response->{status};
	my $content = $response->{content} || '[UNKNOWN CONTENT]';
	my $reason  = $response->{reason}  || '[UNKNOWN REASON]';
	die "ERROR! Status [$status] Content [$content] reason [$reason]\n";
}

sub _handle_response_success {
	my $self    = shift;
	my $content = shift;
	if (my $error = $content->{error}) {
		die "ERROR! [$error->{code}] [$error->{message}]\n";
	}
	if ($content->{message}
		&& $content->{message} eq 'Unauthorized access') {
			die "ERROR! [Unauthorized access]\n";
	}
	return $content
}

1;

__END__

=head1 NAME

WWW::ManageWP::Remote

=head1 DESCRIPTION

Remote class that manages the HTTP connection and JSON encode/decode.

=cut

