package WebService::Strike;

use 5.014000;
use strict;
use warnings;
use parent qw/Exporter/;

our @EXPORT    = qw/strike/; ## no critic (ProhibitAutomaticExportation)
our @EXPORT_OK = qw/strike_query strike/;
our $VERSION = '0.001002';
our $BASE_URL = 'http://getstrike.net/api/torrents/';

use JSON::MaybeXS qw/decode_json/;
use HTTP::Tiny;
use Sort::ByExample qw/sbe/;
use WebService::Strike::Torrent;

sub _ht { HTTP::Tiny->new(agent => "WebService-Strike/$VERSION") }

sub strike_query {
	my (@hashes) = @_;
	my $url = "$BASE_URL/info/?hashes=" . join ',', map { uc } @hashes;
	my $ht = _ht;
	my $response = $ht->get($url);
	die $response unless $response->{success}; ## no critic (RequireCarping)
	$response = decode_json $response->{content};

	die $response unless ref $response eq 'ARRAY'; ## no critic (RequireCarping)
	my $sorter = sbe(\@hashes, {xform => sub { $_[0]->hash }});
	my @torrents = map { WebService::Strike::Torrent->new($_) } @{$response->[1]};
	@torrents = $sorter->(@torrents);
	wantarray ? @torrents : $torrents[0]
}

BEGIN { *strike = \&strike_query }

1;
__END__

=encoding utf-8

=head1 NAME

WebService::Strike - Get torrent info from getstrike.net API

=head1 SYNOPSIS

  use WebService::Strike;
  my $t = strike 'B425907E5755031BDA4A8D1B6DCCACA97DA14C04';
  say $t->title;               # Arch Linux 2015.01.01 (x86\/x64)
  say $t->magnet;              # Returns a magnet link
  my $torrent = $t->torrent;   # Returns the torrent file
  $t->torrent('file.torrent'); # Downloads the torrent file to 'file.torrent'

=head1 DESCRIPTION

Strike API is a service for getting information about a torrent given
its info hash. WebService::Strike is a wrapper for this service.

=over

=item B<strike>(I<@info_hashes>)

Returns a list of hashrefs, one for each info hash. The hashrefs are
blessed into the L<WebService::Strike::Torrent> package. Dies in case
of error.

=item B<strike_query>

Alias for B<strike>. Not exported by default.

=back

=head1 SEE ALSO

L<WebService::Strike::Torrent>, L<http://getstrike.net/api/>, L<WWW::Search::Torrentz>

=head1 AUTHOR

Marius Gavrilescu, E<lt>marius@ieval.roE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2015 by Marius Gavrilescu

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.20.2 or,
at your option, any later version of Perl 5 you may have available.


=cut
