#!/usr/bin/perl
use strict;
use YAML qw(LoadFile);

push @ARGV, 'deps.yml' unless @ARGV;
my $deps_file = shift;
-f $deps_file or die "usage: mkreport [deps.yml]\n";
my $deps = LoadFile($deps_file);

my $report = 'report.html';
my $num = 30;

my @biggest_users = sort {
        scalar keys %{$deps->{$b}{prereqs}} <=> scalar keys %{$deps->{$a}{prereqs}} 
    } keys %$deps;

my @most_popular = sort {
        $deps->{$b}{score} <=> $deps->{$a}{score}
    } keys %$deps;

open(OUT, '>', $report) or die "can't write '$report': $!";

print OUT <<'HTML';
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<!-- Metainformation -->
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Language" content="en" />
<title>CPAN::Dependency Results</title>
<!-- Stylesheets -->
<link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
<h1>CPAN::Dependency Results</h1>
<p>This page was generated by first running the script <i>eg/find_deps</i>, 
which generates the file <i>deps.yml</i>, then by running the script 
<i>eg/mkreport</i>. It's only here to show some of the information you can 
gather using <code>CPAN::Dependency</code>. </p>

<table id="by_score" class="board">
<caption>Distributions sorted by score</caption>
<thead>
  <tr><th>Distribution</th> <th>Score</th></tr>
</thead>
<tbody>
HTML

my $row = <<'ROW';
  <tr>
    <td><a href="http://search.cpan.org/dist/%s" 
        title="Read the documentation of this distribution on Search CPAN"
      >%s</a> [<a href="http://cpan.uwinnipeg.ca/dist/%s"
        title="Read the documentation of this distribution on Kobesearch"
      >mirror</a>]
    </td>
    <td>%d</td>
</tr> 
ROW

for my $dist (@most_popular[0..$num-1]) {
    printf OUT $row, $dist, $dist, $dist, $deps->{$dist}{score}
}

print OUT <<'HTML';
</tbody>
</table>

<table id="by_prereqs" class="board">
<caption>Distributions sorted by number of prerequisites</caption>
<thead>
  <tr><th>Distribution</th> <th>Prereqs</th></tr>
</thead>
<tbody>
HTML

for my $dist (@biggest_users[0..$num-1]) {
    printf OUT $row, $dist, $dist, $dist, scalar keys %{ $deps->{$dist}{prereqs} }
}

my $date = localtime((stat($deps_file))[9]);
print OUT <<"HTML";
</tbody>
</table>

<p style="clear: both"></p>

<p>Generated using data as of $date. </p>

</body>
</html>
HTML

close(OUT);

