package QBit::Application::Model::API::Yandex::BotBlocker;
{
  $QBit::Application::Model::API::Yandex::BotBlocker::VERSION = '0.008';
}

use qbit;

use base qw(QBit::Application::Model::API::HTTP);

sub get {
    my ($self, $uri) = @_;

    my $url = $self->get_option('url', '');
    $url =~ s/\/$//;

    my $response = $self->{'__LWP__'}->get("$url$uri");

    my $content;
    $content = $response->decoded_content() if $response->is_success();

    ldump(
        {
            http_call_uri    => 'GET: ' . $uri,
            http_call_result => {
                status  => $response->code,
                content => $content,
            }
        }
    ) if $self->{'__DEBUG__'};

    throw Exception::API::HTTP $response unless defined($content);

    return $content;
}

sub is_alive {
    my ($self) = @_;

    my $data = $self->get('/is_alive') // '';
    chomp($data);

    return !!$data;
}

sub check {
    my ($self, $ip, $cookie) = @_;

    return {} unless $ip && $cookie;

    my $data = $self->get("/check/$ip/$cookie");

    return {map {split(': ', $_, 2)} split("\n", $data)};
}

sub status {
    my ($self) = @_;

    my $data = $self->get('/status');

    my %result;

    foreach my $analyzer_text (split("-----\n", $data)) {
        my @lines = split("\n", $analyzer_text);
        chomp(@lines);
        my $key = shift(@lines);
        $key =~ s/:$//;

        $result{$key} = [
            map {
                {split(/[ :]/)}
              } @lines
        ];
    }

    return \%result;
}

sub unblock_ip4 {
    my ($self, $ip) = @_;

    return {} unless $ip;

    my $data = $self->get("/mercy/$ip/");

    return {map {split(': ', $_, 2)} split("\n", $data)};
}


sub list_blocked_ips4 {
    return $_[0]->_list_blocked('ips4');
}

sub list_blocked_ips6 {
    return $_[0]->_list_blocked('ips6');
}

sub list_blocked_nets4 {
    return $_[0]->_list_blocked('nets4');
}

sub list_blocked_users {
    return $_[0]->_list_blocked('users');
}

sub _list_blocked {
    my ($self, $type) = @_;

    my @lines = split("\n", $self->get("/list_blocked_$type"));
    chomp(@lines);

    return [
        map {
            my ($time, $data) = split("\t");
            {time => $time, data => $data}
          } @lines
    ];
}

TRUE;
