package DX::Op::Observe;

use DX::ObservationRequired;
use Moo;

with 'DX::Role::Op';

has vars => (is => 'ro', required => 1);
has builder => (is => 'ro', required => 1);

has _arg_map => (is => 'lazy', builder => sub {
  my ($self) = @_;
  my $name = 'arg0';
  +{ map +($name++, $_), @{$self->vars} };
});

sub run {
  my ($self, $state) = @_;
  ($state, my %args) = $self->_expand_args($state, %{$self->_arg_map});
  my @vars = map $state->resolve_value($_), @args{sort keys %args};
  my $observer = $self->builder->(@vars);
  $state->return_from_run(
    DX::ObservationRequired->new(
      observer => $observer,
      resume => $state->then($self->next)
    )
  );
}

1;
