### ----------------------------------------------------
### -- Protocol::MQTT
### -- Licenses: Artistic-2.0
### -- Authors: Leon Timmermans
### -- File: t/03-dispatcher.rakutest
### ----------------------------------------------------
#! raku

use v6.d;

use Test;

use Protocol::MQTT;

subtest 'First', {
	my $dispatcher = Protocol::MQTT::Dispatcher.new;
	my @all;
	$dispatcher.add-filter('#').tap: { @all.push($^message) };
	my @second;
	$dispatcher.add-filter('+/+').tap: { @second.push($^message) };
	my @third;
	$dispatcher.add-filter('a/#').tap: { @third.push($^message) };

	my $message1 = Protocol::MQTT::Message.new(:topic<a>, :payload('a'.encode));
	subtest 'topic=a', {
		$dispatcher.dispatch($message1);
		is-deeply(@all, [$message1], '# matches');
		is-deeply(@second, [], '+/+ doesn\'t match');
		is-deeply(@third, [$message1], 'a/# matches');
	}

	my $message2 = Protocol::MQTT::Message.new(:topic<a/b>, :payload('b'.encode));
	subtest 'topic=a/b', {
		$dispatcher.dispatch($message2);
		is-deeply(@all, [$message1, $message2], '# matches');
		is-deeply(@second, [$message2], '+/+ matches');
		is-deeply(@third, [$message1, $message2], 'a/# matches');
	}

	my $message3 = Protocol::MQTT::Message.new(:topic<$a>, :payload('c'.encode));
	subtest 'topic=$a', {
		$dispatcher.dispatch($message3);
		is-deeply(@all, [$message1, $message2], '# doesn\'t match');
		is-deeply(@second, [$message2], '+/+ doesn\'t match');
		is-deeply(@third, [$message1, $message2], 'a/# doesn\'t match');
	}

	subtest 'resend topic=a/b', {
		$dispatcher.remove-filter('#');
		$dispatcher.dispatch($message2);
		is-deeply(@all, [$message1, $message2], '# sub has been removed');
		is-deeply(@second, [$message2, $message2], '+/+ matches');
		is-deeply(@third, [$message1, $message2, $message2], 'a/# matches');
	}
}

done-testing;


