use Modern::Perl;
use Log::LogMethods::Log4perlLogToString;
use Test::More qw(no_plan);
use HTTP::Response;
use HTTP::Headers;
use HTTP::Request;
use Data::Dumper;
use AnyEvent::Loop;
use Scalar::Util qw(looks_like_number);
use Carp qw(confess);
BEGIN { $SIG{__DIE__} = sub { confess @_ }; }

my $string;
my $module='HTTP::MultiGet::Role';
require_ok($module);
my $class='SomeTestClass';
my $log=LoggerToString($class,$string);

my $self=$class->new;

isa_ok($self,$class);

SKIP: {
  skip '$ENV{RUN_HTTP_TESTS}!=1', 10 unless $ENV{RUN_HTTP_TESTS};

  {
    my $result=$self->google;
    isa_ok($result,'Data::Result');
    ok($result,'Should fetch google.com without issues');
  }

  {
    
    my $result=$self->fail;
    isa_ok($result,'Data::Result') or diag Dumper($result,$self->agent->results);
    ok(!$result,'should have a failed result');
  }
  {
    
    my $result=$self->pass;
    isa_ok($result,'Data::Result') or diag Dumper($result,$self->agent->results);
    ok($result,'should have a good result');
  }
  # 6

  my $count=0;
  $self->que_fail(sub { 
    my ($self,$id,$result)=@_;
    ok(!$result,'Should get called on failure');
    ++$count;
    $self->queue_result(sub { ++$count},$self->new_true) if $count< 5;
  });

  $self->que_pass(sub { 
    my ($self,$id,$result)=@_;
    ok($result,'Should get called on pass');
    ++$count;
    $self->queue_result(sub { ++$count},$self->new_true) if $count< 5;
  });
  $self->que_google(sub { 
    my ($self,$id,$result)=@_;
    ok($result,'Should get called on google request');
    ++$count;
  });

  my $tv;
  TEST_LOOP: {
    $tv=AnyEvent->timer(after=>4,cb=>sub { no warnings;last TEST_LOOP});

    $self->agent->run_next;
    AnyEvent::Loop::run;
    undef $tv;
  }
  cmp_ok($count,'==',5,'should have used all 5 call backs');
 
}

{
  package 
    SomeTestClass;
  use Modern::Perl;
  use Moo;
  use Data::Dumper;
  BEGIN {
  with 'HTTP::MultiGet::Role';
  }
  sub que_google {
    my ($self,$cb)=@_;
    my $req=new HTTP::Request(GET=>'https://google.com');
    return $self->queue_request($req,$cb);
  }

  sub que_fail {
    my ($self,$cb)=@_;
    return $self->queue_result($cb,$self->new_false('I am a failure!'));
  }

  sub que_pass {
    my ($self,$cb)=@_;
    return $self->queue_result($cb,$self->new_true({}));
  }
}
