#!/usr/bin/env perl

use 5.010;
use strict;

=head1 NAME

trrr - search torrents 

=cut

use POSIX qw< ceil >;
use Encode qw< encode >;
use Term::ANSIColor;
use App::Trrr qw< open_app >;
use App::Trrr::KAT qw< kat >;
use App::Trrr::TPB qw< tpb >;
use App::Trrr::Clipboard qw< clip >;

if( $ARGV[0] eq '-h' ){ system("perldoc trrr"); exit }

my @keyword = ();

unless(@ARGV){ 
    my @clip = ();
    my $clip = clip();
    open(my $fh,'<',\$clip->()) || die "cant open string: $!";
    my $line = <$fh>;
    $line =~  s/^\s+//; $line =~ s/\s+$//; push @clip, $line; close $fh;
    #pop @clip 
    for(@clip){ push @keyword, $_ if /[a-z]/ }
}

sub api {
    my $a = shift || "kat";
    my %api = (
        tpb =>  sub { tpb(@_) },
        kat =>  sub { kat(@_) },
    );
    return $api{$a};
}

my $opt = {
    os      =>  "$^O",
    seeds   =>  1,
    api     =>  "kat",
};

for(@ARGV){
    if(/^\-/){
        s/\-//;
        if(/[a-z]/){ $opt->{key} = lc $_ }
        if(/[0-9]+/){ $opt->{seeds} = int $_ } 
        if(/[P]/){ $opt->{api} = "tpb" }
    } else { my $keyword = lc $_; push @keyword, $keyword }
}


my $strip = sub {
    my( $item, $field ) = @_;
    my $term_width  = int `tput cols`; 
    
    my $line = $item->{key} . ' ' . $item->{seeds} . ' ' . "$item->{title}" . ' ' . $item->{category} . ' ' . $item->{size};
    my $max = $term_width - length($line);

    if( $term_width < length($line)){
        my $strip = length($line) - $term_width;
        my $stripped_title = $term_width - $strip + 0;
        $item->{title} = substr( $item->{title},0,$max);
    } 
    my $title = $item->{title};
    my $striped = {};
    $striped->{title} = $title;
    return $striped->{$field}
};


sub show {
    my $key = 'A';
    my( $key_color ) = ();
    my $i = 1;
    my $api = api($opt->{api});
    my @filter = grep { int($_->{seeds}) >= int($opt->{seeds}) } @{ $api->(\@keyword) };
    @filter = sort { $b->{seeds} <=> $a->{seeds} } @filter;
    my @f = splice(@filter,0,15);

    unless(@f){ say colored(['yellow'], 'no results') and exit }
    for(@f){
        if( $i % 2 ){ $key_color = 'black on_white' } else { $key_color = 'white on_black' }

        $_->{key} = $key;
        my $title = $strip->($_,'title');
        say colored([$key_color],$key) . ' ' . colored(['cyan'],$_->{seeds}) . ' ' .  colored(['yellow'],$title) . ' ' . colored(['grey8'],$_->{category}) . ' ' . colored(['bold'],$_->{size}) if defined $_->{key};
        $key++; $i++;
    }
    key(\@f);
}

sub key {
    my $filter = shift;
    get_torrent($filter) if defined $opt->{key};

    if( $opt->{os} eq 'MSWin32' or $opt->{os} eq 'msys' ){ 
        exit unless defined $opt->{key};
    } else {
        exit if defined $opt->{key};
        say colored(['blink'],'^') . ' ' . colored(['grey5 on_grey15'],'P') . colored(['grey15 on_grey5'],'RESS') . colored(['grey5 on_grey15'],'K') . colored(['grey15 on_grey5'],'EY');
        require App::Trrr::HotKey;
        App::Trrr::HotKey->import( 'readkey' ) ;
        $opt->{key} = readkey();
        get_torrent($filter);
    }
}

sub get_torrent {
    my $filter = shift;
    my( $picked ) = grep { $_->{key} eq uc $opt->{key} } @$filter;
    open_app("$picked->{magnet}") if $opt->{key} =~ /[a-o]/;
}

show();


=head1 DESCRIPTION
    
CLI tool to search torrents. Results are sorted by number of seeders and each is mapped to key. Pressing the key with assigned letter will open magnet link in your default client. On iOS, magnet link is placed into clipboard.

=head1 USAGE
    
Search with as many parameters as needed. Uses KAT by default, C<-P> will switch to TPB.

=over 10

C<trrr keyword1 keyword2 keywordN>

C<trrr keyword1 keyword2 keywordN -P>

=back

_

On Linux, start it without any parameter and it'll use clipboard content as keywords. ( needs 'xclip' or 'xsel' to be installed )

=over 10

C<trrr>

=back

_

Limit results which have at least 100 seeders.

=over 10

C<trrr keyword1 keyword2 keywordN -100>

=back

_

To get another torrent from previous search add key as parameter. This is mandatory on Windows running 'Git/Bash for Windows' where you have to specify key on CLI upfront.

=over 10

C<trrr keyword1 keyword2 keywordN -b>

=back

_

See this perdoc.

=over 10

C<trrr -h>

=back

=head1 AUTHOR

Zdenek Bohunek. <zdenek@cpan.org>

App::Trr::HotKey is taken from StackOverflow post by brian d foy

=head1 COPYRIGHT AND LICENSE

Copyright 2016 by Zdenek Bohunek

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

=cut
