package Tak;

use Tak::Loop;
use strictures 1;

our $loop;

sub loop { $loop ||= Tak::Loop->new }

sub loop_until {
  my ($class, $done) = @_;
  return if $done;
  my $loop = $class->loop;
  $loop->loop_once until $_[1];
}

sub await_all {
  my ($class, @requests) = @_;
  @requests = grep !$_->is_done, @requests;
  return unless @requests;
  my %req = map +("$_" => "$_"), @requests;
  my $done;
  my %on_r = map {
    my $orig = $_->{on_result};
    my $tag = $req{$_};
    ($_ => sub { delete $req{$tag}; $orig->(@_); $done = 1 unless keys %req; })
  } @requests;
  my $call = sub { $class->loop_until($done) };
  foreach (@requests) {
    my $req = $_;
    my $inner = $call;
    $call = sub { local $req->{on_result} = $on_r{$req}; $inner->() };
  }
  $call->();
  return;
}

1;
