package CPANPLUS::Dist::Gentoo::Version;

use strict;
use warnings;

use Scalar::Util ();

use overload (
 '<=>' => \&cmp,
 '""'  => \&as_string,
);

our $VERSION = '0.08';

my $int_rx        = qr/\d+/;
my $dotted_num_rx = qr/$int_rx(?:\.$int_rx)*/;

our $version_rx = qr/$dotted_num_rx(?:_p$dotted_num_rx)?(?:-r$int_rx)?/;

sub new {
 my $class = shift;
 $class = ref($class) || $class;

 my $vstring = shift;
 if (defined $vstring) {
  $vstring =~ s/^[._]+//g;
  $vstring =~ s/[._]+$//g;
  if ($vstring =~ /^($dotted_num_rx)(?:_p($dotted_num_rx))?(?:-r($int_rx))?$/) {
   return bless {
    string   => $vstring,
    version  => [ split /\.+/, $1 ],
    patch    => [ defined $2 ? (split /\.+/, $2) : () ],
    revision => [ defined $3 ? $3                : () ],
   }, $class;
  }
 }

 require Carp;
 Carp::croak("Couldn't parse version string '$vstring'");
}

my @parts;
BEGIN {
 @parts = qw/version patch revision/;
 eval "sub $_ { \$_[0]->{$_} }" for @parts;
}

sub cmp {
 my ($v1, $v2, $r) = @_;

 unless (Scalar::Util::blessed($v2) and $v2->isa(__PACKAGE__)) {
  $v2 = $v1->new($v2);
 }

 ($v1, $v2) = ($v2, $v1) if $r;

 for (@parts) {
  my @a = @{ $v1->$_ };
  my @b = @{ $v2->$_ };
  while (@a or @b) {
   my $x = shift(@a) || 0;
   my $y = shift(@b) || 0;
   my $c = $x <=> $y;
   return $c if $c;
  }
 }

 return 0;
}

sub as_string {
 my ($v) = @_;

 my ($version, $patch, $revision) = map $v->$_, @parts;

 $version  = join '.', @$version;
 $version .= '_p' . join('.', @$patch)    if @$patch;
 $version .= '-r' . join('.', @$revision) if @$revision;

 $version;
}

1;
