package DBIx::Data::Collection::Set;

use Moose;
use Method::Signatures::Simple;
use Data::Perl::Stream::Array;

has _store => (is => 'ro', required => 1, init_arg => 'store');

has _column_order => (is => 'ro', required => 1, init_arg => 'column_order');

has _class => (is => 'ro', predicate => '_has_class');

has _member_cache => (is => 'rw', lazy_build => 1);

method _build__member_cache {
  my $stream = $self->_new_raw_stream;
  my @cache;
  while (my ($raw) = $stream->next) {
    push @cache, $self->_inflate($raw);
  }
  \@cache;
}

method _new_raw_stream {
  $self->_store->new_select_command([])->execute;
}

method _inflate ($raw) {
  my @order = @{$self->_column_order};
  my %final;
  @final{@order} = @$raw;
  bless(\%final, $self->_class) if $self->_has_class;
  \%final;
}

method flatten {
  @{$self->_member_cache};
}

method as_stream {
  Data::Perl::Stream::Array->new(array => $self->_member_cache);
}

1;
