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 %orig;
  my %on_r = map {
    my $orig = $orig{$_} = $_->{on_result};
    my $tag = $req{$_};
    ($_ => sub { delete $req{$tag}; $orig->(@_); $done = 1 unless keys %req; })
  } @requests;
  $_->{on_result} = $on_r{$_} for @requests;
  $class->loop_until($done);
  $_->{on_result} = $orig{$_} for @requests;
  return;
}

1;
