package DX::Step::Backtrack;

use DX::DependencyMap;
use DX::Utils qw(format_deps);
use DX::Class;

with 'DX::Role::Step';

has resolution_space => (is => 'ro', isa => ResolutionSpace, required => 1);

sub apply_to {
  my ($self, $ss) = @_;
  my $rspace = $self->resolution_space;
  trace backtrack => [ statement => [
    [ symbol => 'backtrack' ],
    [ statement => [
      [ symbol => 'because' ],
      format_deps($rspace->geometry_depends_on)
    ] ]
  ] ];
  my $dmap = DX::DependencyMap->new_empty
                              ->with_dependencies_for(
                                  backtrack => $rspace->geometry_depends_on
                                );

  foreach my $adj (@{$ss->decisions_taken}) {
    my ($rspace_was, $ss_was) = @$adj;
    $dmap = $dmap->with_dependencies_for(
      backtrack => $rspace_was->geometry_depends_on
    );
    next unless @{$rspace_was->remaining_resolution_space->members};
    trace rspace => [ statement => [
      [ symbol => 'remaining' ],
      @{$rspace_was->remaining_resolution_space->for_deparse->[1]}
    ] ];
    return $ss_was->but(
      next_step => $rspace_was->remaining_resolution_space->next_step
    );
  }
  return $ss->but(next_step => $ss->on_exhaustion_step);
}

1;
