#!/usr/bin/perl

use Net::Delicious;
use Config::Simple;
use Chart::StackedBars;
use List::Util qw(sum);
use File::Spec::Functions;

use strict;
use warnings;

my $input = $ARGV[0];
my $output = $ARGV[1];
my $cfg = Config::Simple->new($input);
my $del = Net::Delicious->new($cfg);

my $it;
my $title;
my $filename;
if (defined $ARGV[2]) {
    if ($ARGV[2] eq 'netcasper') {
	$title =  'statistics of netcasper\'s blog posts';
	$filename = 'blog_post_stat.png';
    }
    else {
	$title = "statistics of netcasper's del.icio.us posts on tag $ARGV[2]";
	$filename = "stat_on_$ARGV[2].png";
    }
    $it = $del->posts_per_date({tag => $ARGV[2]});
}
else {
    $title = 'statistics of netcasper\'s del.icio.us posts';
    $filename = 'delicious_stat.png';
    $it = $del->posts_per_date();
}

my %stat;
while (my $d = $it->next()) {
    my $date = $d->date();
    my ($year, $month, $day) = $date =~ /(\d{4})-(\d{2})-(\d{2})/;
    my $count = $d->count();
    $stat{$year}{$month} += $count;
}

my $chart = Chart::StackedBars->new(800, 600);

my @years = sort keys %stat;
$chart->add_dataset(@years);

my @months = map { sprintf "%02d", $_ } (1 .. 12);
for my $m (@months) {
    my @count_per_month = map { (exists $stat{$_}->{$m}) ? $stat{$_}->{$m} : 0 } @years;
    $chart->add_dataset(@count_per_month);
}

my %properties =
    (
	title => $title,
	text_space => 5,
	precision => 0,
	x_label => 'Year',
	y_label => 'Number of Posts',
	y_grid_lines => 'true',
	legend => 'right',
	legend_labels => ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
			  'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    );
$chart->set(%properties);
$chart->png(catfile($output, $filename));

