### ----------------------------------------------------
### -- Cro::CBOR
### -- Licenses: Artistic-2.0
### -- Authors: Geoffrey Broadwell
### -- File: t/01-http-router-websocket.rakutest
### ----------------------------------------------------
use Test;

use CBOR::Simple;
use Cro::HTTP::Router;
use Cro::HTTP::Server;
use Cro::CBOR;


plan 8;


### BELOW TESTS ADAPTED NEARLY VERBATIM FROM THE JSON TESTS FOR CRO::WebSocket


my $app = route {
    get -> 'parser-serializer' {
        web-socket
            :body-parsers(Cro::CBOR::WebSocket::BodyParser),
            :body-serializers(Cro::CBOR::WebSocket::BodySerializer),
            -> $incoming {
                supply whenever $incoming -> $message {
                    my $body = await $message.body;
                    $body<added> = 42;
                    $body<updated>++;
                    emit $body;
                }
            }
    }

    get -> 'cbor' {
        web-socket :cbor, -> $incoming {
            supply whenever $incoming -> $message {
                my $body = await $message.body;
                $body<added> = 4242;
                $body<updated>++;
                emit $body;
            }
        }
    }
}

my $http-server = Cro::HTTP::Server.new(port => 3006, application => $app);
$http-server.start();
END $http-server.stop();

{
    my $c = await Cro::WebSocket::Client.connect: 'http://localhost:3006/parser-serializer';
    my $reply-promise = $c.messages.head.Promise;
    $c.send(cbor-encode({ updated => 99, kept => 'xxx' }));
    my $reply = await $reply-promise;
    my $parsed;
    lives-ok { $parsed = cbor-decode await $reply.body },
        'Get back valid CBOR from websocket endpoint with CBOR parser/serializer endpoint';
    is $parsed<updated>, 100, 'Expected data returned (1)';
    is $parsed<kept>, 'xxx', 'Expected data returned (2)';
    is $parsed<added>, 42, 'Expected data returned (3)';
    $c.close;
}

{
    my $c = await Cro::WebSocket::Client.connect: 'http://localhost:3006/cbor';
    my $reply-promise = $c.messages.head.Promise;
    $c.send(cbor-encode({ updated => 102, kept => 'xxxy' }));
    my $reply = await $reply-promise;
    my $parsed;
    lives-ok { $parsed = cbor-decode await $reply.body },
        'Get back valid CBOR from websocket endpoint that uses :cbor';
    is $parsed<updated>, 103, 'Expected data returned (1)';
    is $parsed<kept>, 'xxxy', 'Expected data returned (2)';
    is $parsed<added>, 4242, 'Expected data returned (3)';
    $c.close;
}


done-testing;


