package Object::Builder;

use Module::Runtime qw(use_module);
use Moo;

our $VERSION = '0.000001'; # 0.0.1

$VERSION = eval $VERSION;

has class => (
  is => 'rw', lazy => 1, builder => 1,
  trigger => sub { shift->_clear_final_class },
);

sub _build_class { die "No default class set" }

has roles => (
  is => 'rw', lazy => 1, builder => 1,
  trigger => sub { shift->_clear_final_class },
  clearer => 'reset_roles',
);

after reset_roles => sub { shift->_clear_final_class };

sub _build_roles { [] }

has _final_class => (is => 'lazy', clearer => 1);

sub _build__final_class {
  my ($self) = @_;
  my $class = use_module($self->class);
  if (my @roles = @{$self->roles}) {
    require Moo::Role;
    return Moo::Role->create_class_with_roles($class, @roles);
  } else {
    return $class;
  }
}

after _clear_final_class => sub { shift->clear_object };

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

has arguments => (
  is => 'rw', builder => 1,
  trigger => sub { shift->_clear_final_arguments },
  clearer => 'reset_arguments',
);

after reset_arguments => sub { shift->_clear_final_arguments };

sub _build_arguments { {} }

has argument_filter => (
  is => 'rw', builder => 1,
  trigger => sub { shift->_clear_final_arguments },
  clearer => 'reset_argument_filter',
);

sub _build_argument_filter { sub { shift } }

has _final_arguments => (is => 'lazy', clearer => 1);

after _clear_final_arguments => sub { shift->_clear_object };

sub _build__final_arguments {
  my ($self) = @_;
  $self->argument_filter->($self->arguments);
}

has object => (is => 'lazy', clearer => 1);

sub _build_object {
  my ($self) = @_;
  $self->_final_class->${\$self->constructor}($self->_final_arguments);
}

sub BUILD {
  my ($self, $args) = @_;
  unless (
    $args->{object} or $args->{class}
    or ($self->can('_build_class') ne __PACKAGE__->can('_build_class')
  ) {
    die "No static object passed, and no class supplied or defaulted";
  }
}

1;

=head1 NAME

Object::Builder - An object for building other objects.

=head1 SYNOPSIS

=head1 DESCRIPTION

=head1 AUTHOR

 mst - Matt S. Trout (cpan:MSTROUT) <mst@shadowcat.co.uk>

=head1 CONTRIBUTORS

None yet - maybe this software is perfect! (ahahahahahahahahaha)

=head1 COPYRIGHT

Copyright (c) 2012 the Object::Builder L</AUTHOR> and L</CONTRIBUTORS>
as listed above.

=head1 LICENSE

This library is free software and may be distributed under the same terms
as perl itself.
