package DX::State;

use Moo;

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

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

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

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

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

sub scope_var {
  my ($self, $name) = @_;
  $self->by_id->{$self->scope->{$name}};
}

sub bind_stream_then {
  my ($self, $var, $stream, $then) = @_;
  warn "Binding ".$var->id." to $stream";
  my $bound = $var->with_stream($stream);
  $self->new(%$self,
    by_id => { %{$self->by_id}, $var->id => $bound },
    next_op => $then
  )->mark_choice($bound);
}

sub mark_choice {
  my ($self, $var) = @_;
  $self->new(%$self,
    last_choice => [ $self, $var ]
  );
}

sub backtrack {
  my ($self) = @_;
  my ($state, $var) = ($self);
  while (($state, $var) = @{$state->last_choice}) {
    $var->bound_value; $var->clear_bound_value;
    return $state->mark_choice($var) unless $var->bound_stream->is_exhausted;
  }
  die "Out of options";
}

sub then {
  my ($self, $then) = @_;
  $self->new(%$self, next_op => $then);
}

sub run {
  my ($state) = @_;
  while (my $op = $state->next_op) {
    $state = $op->run($state);
  }
  return $state;
}

1;
