#!/usr/bin/env raku

use Timer::Stopwatch;

my $channel = Channel.new;

my $supplier = Supplier.new;
my $supply   = $supplier.Supply;

my $timer = Timer::Stopwatch.new;

my @batch;
start react {
    whenever $supply {
        note "Got event: $_";
        if $timer.reset: 1 {
            note 'Received while within window';
        }
        else {
            note 'Received after timer';
            $channel.send: @batch.clone if @batch;
            @batch = ();
        }

        @batch.push: $_;
    }
    whenever Promise.kept {
        note 'Sent some initial messages';
        $supplier.emit: $_ for < a b c d >;
    }
    whenever $timer {
        note 'Timer expired!';
        $channel.send: @batch.clone;
        @batch = ();
    }
    whenever Promise.in: 2 {
        note 'Sending more messages';
        $supplier.emit: $_ for < e f g h i >;
    }
    whenever Promise.in: 4 {
        $timer.stop;
    }
    whenever $timer.Promise {
        note "$_ seconds since the last reset";
        $channel.close;
        done;
    }
}

loop {
    CATCH { last when X::Channel::ReceiveOnClosed }
    LAST note 'Done';

    with $channel.receive -> @batch {
        note 'Got a batch~';
        dd @batch;
    }
}
