package CatalystX::UriFor::Curried;
use MooseX::Role::Parameterized;
use Moose::Autobox;
use MooseX::Types::Moose qw/ Str ArrayRef /;
use Scalar::Util qw/ weaken /;
use namespace::autoclean;

parameter method_name => (
    isa => Str,
    required => 1,
);

parameter stash_captures => (
    isa => ArrayRef[Str],
    required => 1,
);

role {
    my $p = shift;

    my $method_name = $p->method_name;
    my $stash_captures => $p->stash_captures;

    method $method_name => sub {
        my ($ctx, $action_or_private_path, $captures, @args)  = @_;
        my $weak_ctx = $ctx; # Just for safety so it can't be closed over.
        weaken($weak_ctx);
        my $params = ref($args[-1]) eq 'HASH' ? pop(@args) : {};
        if (ref($captures) eq 'ARRAY' || (!$captures && !scalar(@args))) { # FIXME BUG IN THIS LOGIC
            $captures ||= [];
            foreach my $name_or_sub ($stash_captures->flatten) {
                unshift(@$captures, ref($name_or_sub) eq 'CODE' ? $name_or_sub->($weak_ctx) : $ctx->stash->{$name_or_sub});
            }
            $ctx->uri_for_action($action_or_private_path, $captures, @args, $params);
        }
    };

};

1;

=head1 NAME

CatalystX::UriFor::Curried - 

=head1 DESCRIPTION

=head1 METHODS

=head1 BUGS

=head1 AUTHOR

=head1 COPYRIGHT & LICENSE

Copyright 2009 the above author(s).

This sofware is free software, and is licensed under the same terms as perl itself.

=cut

