#!/usr/bin/perl
#
# Copyright 2014 - Giovanni Simoni
#
# This file is part of PFT.
#
# PFT is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# PFT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with PFT.  If not, see <http://www.gnu.org/licenses/>.
#
=head1 NAME

pft blog - Edit a blog entry

=head1 SYNOPSYS

pft blog [options] <Title...>

=head1 DESCRIPTION

Edit a blog entry

=head1 OPTIONS

=over

=item --year=<y> | -y <y>

=item --month=<m> | -m <m>

=item --day=<d> | -d <d>

=item --author=<name> | -a <name>

=item --tag=<tag> | -t <tag>

=item --resume | -r

=item --back=<count> | -b <count>

=item --help | -h

=back


=cut

use strict;
use warnings;

use App::PFT;
use App::PFT::Struct::Tree;
use App::PFT::Data::Date;
use App::PFT::Struct::Conf qw/cfg_load $ROOT $AUTHOR/;

use Pod::Usage;
use FindBin;

use Getopt::Long qw/GetOptionsFromArray/;
Getopt::Long::Configure qw/bundling/;

my %opts;
my %datespec;

GetOptions(
    'year|y=i'      => \$datespec{year},
    'month|m=s'     => \$datespec{month},
    'day|d=i'       => \$datespec{day},
    'author|a=s'    => sub { $opts{author} = $_[1] },
    'tag|t=s@'      => sub { push @{$opts{tags}}, $_[1] },
    'resume|r!'     => sub { $opts{back} = 0 },
    'back=i'        => sub { $opts{back} = int($_[1]) },
    'help|h!'       => sub {
        pod2usage
            -exitval => 1,
            -verbose => 2,
            -input => App::PFT::help_of 'blog',
    },
) or exit 1;

cfg_load App::PFT::findroot -die => 1;

my $tree = App::PFT::Struct::Tree->new(basepath => $ROOT);
my $entry;

if (defined $opts{back}) {
    $entry = eval {
        $tree->latest_entry($opts{back});
    };
    if ($@) {
        die 'Cannot go back by ', $opts{back}, ': ', $@;
    }
} else {
    unless (@ARGV) {
        say STDERR "Usage: $App::PFT::Name blog [options] <title>";
        exit 1;
    }

    $entry = $tree->entry(
        title => join(' ', @ARGV),
        date => App::PFT::Data::Date->new(
            %datespec,
            -fill => 'now',
        ),

        # defaults
        author => $AUTHOR,
        tags => [],

        # override
        %opts,
    );
}

$entry->open('a');
$entry->edit;
