#!/usr/bin/perl

use lib 'lib';
use Perl::APIReference;
use Perl::APIReference::Generator;
use File::Copy qw(move);

use strict;
use warnings;

sub sortable {
  my $v = shift;
  $v =~ s/([0-9]+)\.([0-9]+)\.([0-9]+)/sprintf("%s.%03d.%03d", $1, $2, $3)/e;
  return $v;
}

opendir D, 'data';
my @list = readdir D;
@list = grep /perlapi/, @list;
@list = grep /xz/, @list;
map {s/perlapi.(.*).pod.xz/$1/} @list;
@list = sort {sortable($a) cmp sortable($b)} @list;
foreach my $v(@list) {
  print "Processing: $v\n";
  my $data_xz = "./data/perlapi." . $v . ".pod.xz";
  my $data = "./data/perlapi." . $v . ".pod";
  my $target = "./lib/Perl/APIReference/V" . $v . ".pm";
  my $perl_ver = "$v";
  $target  =~ s/([0-9]+)\.([0-9]+)\.([0-9]+)/sprintf("%s_%03d_%03d", $1, $2, $3)/e;
  $perl_ver =~ s/([0-9]+)\.([0-9]+)\.([0-9]+)/sprintf("%s.%03d%03d", $1, $2, $3)/e;
  $perl_ver =~ s/000$//;    # 5.006000 => 5.006
  my $generated = "$target";
  $generated =~ s/.*\///g;

  my $api = Perl::APIReference::Generator->parse(
      file => $data,
      perl_version => $perl_ver,
  );

  if ($api) {
      $api->_dump_as_class();
  }

  move($generated, $target) or die "Error while moving $generated to $target: $!\n";
}
