use strict;

use UniEvent;
use UniEvent::WebSocket;


$SIG{PIPE} = 'IGNORE';

my $srv = UniEvent::WebSocket::Server->new({
    locations => [{host => "dev", port => 6667}],
    connection => {check_utf8 => 1},
});
$srv->run;

$srv->connection_event->add(sub {
    my (undef, $client) = @_;

    $client->message_event->add(sub {
        my (undef, $msg) = @_;

        warn $msg->error, " - ", $msg->payload;
        exit -1;
    });
});

my $data = [
    [0xc0, 0xaf],
    [0xe0, 0x80, 0xaf],
    [0xf0, 0x80, 0x80, 0xaf],
    [0xc1, 0xbf],
    [0xfc, 0x83, 0xbf, 0xbf, 0xbf, 0xbf],
    [0x80],
    [0xbf],
    [0x80, 0xbf],
    [0xc0, 0x20],
    [0xdf, 0x20],
    [0xe0, 0x20],
    [0xef, 0x20],
    [0xf0, 0x20],
    [0xf7, 0x20],
    [0xf8, 0x20],
    [0xfb, 0x20],
    [0xfc, 0x20],
    [0xfd, 0x20],
    [0xc0],
    [0xe0, 0x80],
    [0xf0, 0x80, 0x80],
    [0xf8, 0x80, 0x80, 0x80],
    [0xfc, 0x80, 0x80, 0x80, 0x80],
    [0xdf],
    [0xef, 0xbf],
    [0xf7, 0xbf, 0xbf],
    [0xfb, 0xbf, 0xbf, 0xbf],
    [0xfd, 0xbf, 0xbf, 0xbf, 0xbf],
    [0xc0, 0x80],
    [0xe0, 0x80, 0x80],
    [0xf0, 0x80, 0x80, 0x80],
    [0xf8, 0x80, 0x80, 0x80, 0x80],
    [0xfc, 0x80, 0x80, 0x80, 0x80, 0x80],
    [0xfe],
    [0xff],
    [0x20, 0xff],
    [0xed, 0xa0, 0x80],
    [0xed, 0xad, 0xbf],
    [0xed, 0xac, 0x80],
    [0xed, 0xaf, 0xbf],
    [0xed, 0xb0, 0x80],
    [0xed, 0xbe, 0x80],
    [0xed, 0xbf, 0xbf],
    [0xed, 0xa0, 0x80, 0xed, 0xb0, 0x80],
];

sub gen {
    my $entry = shift @$data;
    exit(0) unless $entry;

    my $client = UniEvent::WebSocket::Client->new;
    $client->connect("dev", 0, 6667);
    $client->connect_callback(sub {
        exit(-2) if $_[2]; # err

        $client->send(payload => join('', map {chr($_)} @$entry), opcode => Protocol::WebSocket::Fast::OPCODE_TEXT);
    });
    $client->close_callback(sub {
        undef $client;
        gen();
    });
}

gen();

# THIS EXISTS WITH 0 CODE ON SUCCESS
# AND NEGATIVE ON ERRORS

UE::Loop->default_loop->run;
