package DX::ResolvedPropositionSet;

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

has dependency_map => (is => 'ro', isa => DependencyMap, required => 1);

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

has scope_depth => (is => 'ro', isa => Int, required => 1);

sub resolved_count { scalar @{$_[0]->propositions} }

sub new_empty {
  my ($class) = @_;
  $class->new(
    propositions => [],
    dependency_map => DX::DependencyMap->new_empty,
    scope_depth => 0,
  );
}

sub with_resolution_for {
  my ($self, $prop, $deps) = @_;
  my $id = my @already = @{$self->propositions};
  my $new_depmap = $self->dependency_map
                        ->with_entry_for($id, $deps);
  ref($self)->new(
    dependency_map => $new_depmap,
    propositions => [ @already, $prop ],
    scope_depth => $self->scope_depth,
  );
}

sub with_updated_dependencies_for {
  my ($self, $prop, $deps) = @_;
  my @props = @{$self->propositions};
  my ($id) = grep $props[$_] eq $prop, 0..$#props;
  # 0 is valid, undef means the grep failed
  die "Unable to find $prop in proplist" unless defined $id;
  my $new_depmap = $self->dependency_map
                        ->with_entry_for($id, $deps);
  ref($self)->new(
    dependency_map => $new_depmap,
    propositions => \@props,
    scope_depth => $self->scope_depth,
  );
}

sub but_expire_for {
  my ($self, @events) = @_;
  my ($depmap, @expired_ids) = $self->dependency_map
                                    ->but_expire_dependents_of(@events);
  # Didn't expire anything? Don't clone self
  return $self if $depmap eq $self->dependency_map;
  my $props = $self->propositions;
  return (
    $self->but(dependency_map => $depmap),
    map $props->[$_], @expired_ids
  );
}

sub dependencies_for {
  my ($self, $prop) = @_;
  my @props = @{$self->propositions};
  my ($id) = grep $props[$_] eq $prop, 0..$#props;
  # 0 is valid, undef means the grep failed
  die "Unable to find $prop in proplist" unless defined $id;
  return $self->dependency_map->dependencies_for($id)||[];
}

1;
