package Bryar::DataSource::FlatFile::ParsedDate;
use base 'Bryar::DataSource::FlatFile';
our $VERSION = '1.0';
use Cwd;
use File::Basename;
use Bryar::Document;
use File::Find::Rule;
use Date::Parse;
use strict;
use warnings;
use Carp;

=head1 NAME

Bryar::DataSource::FlatFile::ParsedDate - Blog from flat files with human-readable dates inside

=head1 SYNOPSIS

    1st January 1970, 20:12

    Title

    Stuff

=head1 DESCRIPTION

See L<Bryar::DataSource::FlatFile>

=cut

sub make_document {
    my ($self, $file) = @_;
    return unless $file;
    open(my($in), $file) or return;
    local $/ = "\n";
    my $who = getpwuid((stat $file)[4]);

    my $when  = <$in>;

    my $title = <$in>;
    chomp $title;
    local $/;
    my $content = <$in>;
    close $in;
    my $id = $self->file_to_id($file);

    my $comments = [];
    $comments = [_read_comments($id, $id.".comments") ]
        if -e $id.".comments";

    chomp $when;
    $when  = str2time($when);

    my $dir = dirname($id);
    $dir =~ s{^\./?}{};
    my $category = $dir || "main";
    return Bryar::Document->new(
        title    => $title,
        content  => $content,
        epoch    => $when,
        author   => $who,
        id       => $id,
        category => $category,
        comments => $comments
    );
}

sub _read_comments {
    my ($id, $file) = @_;
    open COMMENTS, $file or die $!;
    local $/;
    # Watch carefully
    my $stuff = <COMMENTS>;
    my @rv;
    for (split /-----\n/, $stuff) {
        push @rv,
            Bryar::Comment->new(
                id => $id,
                map {/^(\w+): (.*)/; $1 => $2 } split /\n/, $_
            )
    }
    return @rv;
}

1;
