#!/usr/bin/perl

use warnings;
use strict;

use DBI;
use OpenDict;
use Template;
use Digest::MD5 qw(md5_hex);


use Data::Dumper;

binmode(STDOUT, ":utf8");
binmode(STDERR, ":utf8");

# two_words();
news_atom();

sub news_atom {
    my $dbh  = DBI->connect("dbi:SQLite:dbname=news.db","","") or die;
    $dbh->{sqlite_unicode} = 1;
    my $sth  = $dbh->prepare("SELECT * FROM news ORDER BY year DESC,month DESC,day DESC LIMIT 10;");
    my $tt   = Template->new({INTERPOLATE => 1}) || die "$Template::ERROR\n";
    my $data = {
                subtitle    => 'Novidades',
                update_date => mkDate(time),
                full_md5    => md5_hex(mkDate(time)),
                entries     => [],
               };
    my @row;
    $sth->execute;
    while (@row = $sth->fetchrow_array) {
        push @{$data->{entries}},
          {
           title => $row[3],
           url   => 'http://dicionario-aberto.net/news',
           md5   => md5_hex(sprintf("%04d-%02d-%02dT00:00Z", @row[0..2])),
           date  => sprintf("%04d-%02d-%02dT00:00Z", @row[0..2]),
           text  => $row[4],
          };
    }
    open TMPL, "<:encoding(UTF-8)", "atom_tmpl.xml";
    $tt->process(\*TMPL, $data, "news.xml", binmode => ':utf8');
}

sub two_words {
    my $xml = OpenDict->connect;
    sorteia($xml);
    my $tt = Template->new({INTERPOLATE  => 1}) || die "$Template::ERROR\n";
    my $data = {
                subtitle => 'Duas palavras por dia',
                update_date => mkDate(time),
                full_md5 => md5_hex(mkDate(time)),
                entries => [],
               };
    open V, "-|:encoding(UTF-8)", "head -n 28 visited_terms.lst";
    while(<V>) {
        chomp;
        my ($l,$r) = split /===/;
        push @{$data->{entries}},
          {
           title => $l,
           url => "http://dicionario-aberto.net/bin/dic.pl?word=$l",
           md5 => md5_hex(mkDate($r)),
           date => mkDate($r),
           text => join("\n", map {
               my ($t,$def, $class) = $xml->xml2html($_);
               "<div class='term$class'><h3>$</h3><div class=\"def\">$def</div></div>";
           } $xml->xml_entries($l)),
          };
    }
    open TMPL, "<:encoding(UTF-8)", "atom_tmpl.xml";
    $tt->process(\*TMPL, $data, "atom.xml", binmode => ':utf8');
}

sub sorteia {
    my $xml = shift;
    my %visited_terms = ();
    my @visited_terms = ();


    # Load the terms already visited
    #
    if (-f "visited_terms.lst") {
        open V, "<:encoding(UTF-8)", "visited_terms.lst";
        while(<V>) {
            chomp;
            my ($l,$r) = split /===/;
            $visited_terms{$l}=$r;
            unshift @visited_terms, $l;
        }
        close V;
    }

    for (1..2) {
        my $word;
        do {
            $word = $xml->randomWord;
        } while (exists $visited_terms{$word});
        $visited_terms{$word}=time;
        unshift @visited_terms, $word;
        print STDERR " -- $word\n";
        sleep 1;
    }

    open V, ">:encoding(UTF-8)" ,"visited_terms.lst";
    for my $word (@visited_terms) {
        print V "$word===",$visited_terms{$word},"\n";
    }
    close V;
}


sub mkDate {
    my $time = shift;
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time);
    return sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", $year+1900, $mon+1, $mday, $hour, $min, $sec)
}










