package Alien::Build::Plugin::Prefer::SortVersions;

use strict;
use warnings;
use Alien::Build::Plugin;

# ABSTRACT: Plugin to sort candidates by most recent first
our $VERSION = '0.01'; # VERSION

has 'filter'   => qr//;
has '+version' => qr/([0-9\.]+)/;

sub init
{
  my($self, $meta) = @_;
  
  $meta->add_requires('share' => 'Sort::Versions' => 0);
  
  $meta->register_hook( prefer => sub {
    my(undef, $res) = @_;
    
    my $cmp = sub {
      my($A,$B) = map { $_ =~ $self->version } @_;
      Sort::Versions::versioncmp($B,$A);
    };
    
    my @list = sort { $cmp->($a->{filename}, $b->{filename}) }
               grep { $_->{filename} =~ $self->filter && $_->{filename} =~ $self->version }
               @{ $res->{list} };
    
    return {
      type => 'list',
      list => \@list,
    };
  });
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Alien::Build::Plugin::Prefer::SortVersions - Plugin to sort candidates by most recent first

=head1 VERSION

version 0.01

=head1 AUTHOR

Graham Ollis <plicease@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2017 by Graham Ollis.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
