### ----------------------------------------------------
### -- Humming-Bird
### -- Licenses: MIT
### -- Authors: Rawley Fowler
### -- File: it/01-basic.rakutest
### ----------------------------------------------------
use v6;

use Test;

use Humming-Bird::Core;
use Test::Util::ServerPort;
use Cro::HTTP::Client;

my $body = 'abc';

get('/', -> $request, $response {
    $response.write($body);
});

my $content;
post('/form', -> $request, $response {
    $content := $request.content;
    $response;
});

get('/saytest', -> $request, $response {
    $response.status(201);
    say "FOO!";
});

my $port = get-unused-port;

listen($port, :no-block);

sleep 1; # Yes, yes, I know

my $base-uri = "http://0.0.0.0:$port";

my $client = Cro::HTTP::Client.new: :$base-uri;
my $response;
lives-ok({ $response = await $client.get('/') });

ok $response, 'Was response a success?';
is (await $response.body-text), 'abc', 'Is response body OK?';

lives-ok({ $response = await $client.get('/saytest') });

ok $response, 'Was saytest response a success?';
is $response.status, 201, 'Was saytest response code correct?';

# TODO: Fix this.
my $blob = slurp('t/static/baobao.jpg', :bin);
lives-ok({
    $response = await $client.post: '/form',
    content-type => 'multipart/form-data',
    content-length => $blob.bytes,
    body => [
        name => 'foo',
        age => 123,
        Cro::HTTP::Body::MultiPartFormData::Part.new(
            headers => [Cro::HTTP::Header.new(
                name => 'Content-type',
                value => 'image/jpeg'
            )],
            name => 'photo',
            filename => 'baobao.jpg',
            body-blob => $blob
        )
    ];
}, "Can we send the baobao?");

await $response.body;

ok $content.<name>, 'Is multipart param 1 good?';
ok $content.<age>, 'Is multipart param 2 good?';
ok $content.<photo>, 'Is multipart param 3 (file param) good?';
is $content.<photo>.<body>, $blob, 'Is file param correct data?';
is $content.<photo>.<filename>, 'baobao.jpg', 'Is the filename correctly parsed?';

done-testing;


