package DX::RuleSet;

use Moo;
use DX::Op::CallRule;
use DX::Op::MemberOf;
use DX::Op::MemberLookup;
use DX::Op::ApplyConstraint;
use DX::Op::Return;
use List::Util qw(reduce);

has rules => (is => 'ro', default => sub { {} });

sub add_rule {
  my ($self, $name, $vars, @body) = @_;
  my $full_name = join('/', $name, scalar @$vars);
  push @{$self->rules->{$full_name}}, $self->_make_rule($vars, @body);
  return $self;
}

sub _make_rule {
  my ($self, $vars, @body) = @_;
  my $head = reduce { $b->but(next => $a) }
               DX::Op::Return->new,
               reverse map $self->expand(@$_), @body;
  [ $vars, $head ];
}

sub expand {
  my ($self, $type, @rest) = @_;
  $self->${\"_expand_${type}"}(@rest);
}

sub _expand_call {
  my ($self, $name, @args) = @_;
  DX::Op::CallRule->new(rule_name => $name, rule_args => \@args);
}

sub _expand_member_of {
  my ($self, $member_var, $coll_name) = @_;
  DX::Op::MemberOf->new(
    member_var => $member_var,
    coll_name => $coll_name,
  );
}

sub _expand_member_lookup {
  my ($self, $member_var, $coll_name, $key_name, $key_var) = @_;
  DX::Op::MemberLookup->new(
    member_var => $member_var,
    coll_name => $coll_name,
    key_name => $key_name,
    key_var => $key_var
  );
}

sub _expand_constrain {
  my ($self, $vars, $constraint) = @_;
  DX::Op::ApplyConstraint->new(
    vars => $vars,
    constraint => $constraint
  );
}

1;
