#!/usr/bin/perl

use Net::Delicious;
use Config::Simple;
use YAML qw(DumpFile);
use Encode;
use DateTime;
use DateTime::Duration;
use DateTime::Format::W3CDTF;

use strict;
use warnings;

sub format_datetime {
    my $datetime = shift;
    return DateTime::Format::W3CDTF->format_datetime($datetime);
}

sub parse_datetime {
    my $str = shift;
    return DateTime::Format::W3CDTF->parse_datetime($str);
}

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

my $time_zone = "Asia/Shanghai";

my $last_update_date = parse_datetime($del->update);
$last_update_date->set_time_zone($time_zone);

my $now = DateTime->now(time_zone => $time_zone);
my $duration = $now - $last_update_date;

unless ($duration->delta_days >= 1) {
    print STDERR "Don't touch http://del.icio.us/ more than once in a day.\n";
    exit 0;
}

my $next_week = $now + DateTime::Duration->new(weeks => 1);

my $now_str = format_datetime($now);
my $next_week_str = format_datetime($next_week);

my $it = $del->all_posts_for_tag({tag => 'netcasper'});

my %tag_count;

while (my $p = $it->next()) {
    my @tags = split ' ', $p->tags ();
    ++$tag_count{encode_utf8($_)} for @tags;
}

unless (scalar keys %tag_count == 0) {
    my %tags =
	(
	    tag_count => \%tag_count,
	    update_date => $now_str,
	    next_update => $next_week_str,
	);

    my $output = $ARGV[1];
    if (defined $output) {
	DumpFile ("$output/delicious.yml", \%tags);
    }
    else {
	DumpFile ('delicious.yml', \%tags);
    }
}
