package DX::Step::Normal;

use Types::Standard qw(ArrayRef);
use DX::Utils qw(deparse);
use DX::Class;

with 'DX::Role::Step';

has actions => (is => 'ro', isa => ArrayRef[Action], required => 1);

has depends_on => (is => 'ro', isa => DependencyGroupList, required => 1);

has resolves => (is => 'ro', isa => Proposition);

has alternative_step => (is => 'ro', isa => Step);

sub but_first {
  my ($self, @actions) = @_;
  $self->but(actions => [ @actions, @{$self->actions} ]);
}

sub but_with_dependencies_on {
  my ($self, @deps) = @_;
  $self->but(depends_on => [ @{$self->depends_on}, @deps ]);
}

sub apply_to {
  my ($self, $ss) = @_;
  my $old_hyp = $ss->current_hypothesis;
  trace 'step.apply.old_hyp '.$self => $old_hyp;
  trace 'step.apply.actions '.$self => $self->actions;
  my $new_hyp = $self->_apply_to_hyp($old_hyp);
  return (undef, $self->alternative_step) unless $new_hyp;
  trace 'step.apply.new_hyp '.$self => $new_hyp;
  my $ns = DX::Step::InvokeNextPredicate->new(
    proposition => $ss->next_proposition($new_hyp)
  );
  return (
    $ss->but(
      current_hypothesis => $new_hyp,
      next_step => $ns,
    ),
    $self->alternative_step
  );
}

sub _apply_to_hyp {
  my ($self, $old_hyp) = @_;
  return undef unless my $hyp = $old_hyp->with_actions(@{$self->actions});
  return $hyp->with_resolution($self->resolves, $self->depends_on);
}

1;
