### ----------------------------------------------------
### -- Net::HTTP
### -- Licenses: Artistic-2.0
### -- Authors: ugexe
### -- File: xt/500-transport.rakutest
### ----------------------------------------------------
use Test:ver<6.c+>;
plan 4;

use Net::HTTP::Transport;
use Net::HTTP::URL;
use Net::HTTP::Request;

subtest 'Transfer-Encoding: chunked [IO::Socket::INET]' => {
    my $url = Net::HTTP::URL.new('http://anglesharp.azurewebsites.net/Chunked');
    my $req = Net::HTTP::Request.new: :$url, :method<GET>,
        header => :Connection<keep-alive>, :User-Agent<raku-net-http>;

    my $transport = Net::HTTP::Transport.new;
    my $res       = $transport.round-trip($req);
    my $decoded   = $res.body.decode;

    is $decoded.chars, 353;
}

subtest 'Threads: start { $transport.round-trip($req) }' => {
    my $url = Net::HTTP::URL.new('http://anglesharp.azurewebsites.net/Chunked');
    my $req = Net::HTTP::Request.new: :$url, :method<GET>,
        header => :Connection<keep-alive>, :User-Agent<raku-net-http>;

    my $instances = 5;
    my $transport = Net::HTTP::Transport.new;
    my @responses = await (start { $transport.round-trip($req) } xx $instances);

    for @responses -> $res {
        my $decoded = $res.body.decode;
        is $decoded.chars, 353;
    }
}


if Net::HTTP::Dialer.?can-ssl {
    subtest 'Transfer-Encoding: chunked [IO::Socket::SSL]' => {
        my $url = Net::HTTP::URL.new('https://jigsaw.w3.org/HTTP/ChunkedScript');
        my $req = Net::HTTP::Request.new: :$url, :method<GET>,
            header => :Connection<close>, :User-Agent<raku-net-http>;

        my $transport = Net::HTTP::Transport.new;
        my $res       = $transport.round-trip($req);
        my $decoded   = $res.body.decode;

        is $decoded.lines.grep(/^0/).elems, 1000;
        is $decoded.chars, 72200;
    }
}
else {
    ok 1, "Skip: Can't do SSL. Is IO::Socket::SSL available?";
}

if Net::HTTP::Dialer.?can-ssl {
    subtest 'Threads: start { $transport.round-trip($req) } [IO::Socket::SSL]' => {
        my $url = Net::HTTP::URL.new('https://jigsaw.w3.org/HTTP/ChunkedScript');
        my $req = Net::HTTP::Request.new: :$url, :method<GET>,
            header => :Connection<close>, :User-Agent<raku-net-http>;

        my $instances = 5;
        my $transport = Net::HTTP::Transport.new;
        my @responses = await (start { $transport.round-trip($req) } xx $instances);

        for @responses -> $res {
            is $res.body.decode.lines.grep(/^0/).elems, 1000;
        }
    }
}
else {
    ok 1, "Skip: Can't do SSL. Is IO::Socket::SSL available?";
}

done-testing;


