#!/usr/bin/perl

# a simple example script to print all due todos

# workaround for dzil
package remind_due_todos;
BEGIN {
  $remind_due_todos::VERSION = '0.05';
}

use 5.010;
use strict;
use warnings;
use Log::Any qw($log);

use DateTime;
use Org::Parser;
use Sub::Spec::CmdLine qw(run);
our %SPEC;

$SPEC{get_due_todos} = {
    summary => 'Return all due TODOs',
    args    => {
        files => ['array*' => {
            of         => 'str*',
            arg_pos    => 0,
            arg_greedy => 1,
        }],
        days_before => [int => {
            default => 0
        }],
    },
};
sub get_due_todos {
    my %args = @_;
    $args{days_before} //= 0;

    my $today = DateTime->today;

    my @res;
    for my $file (@{ $args{files} }) {
        $log->debug("Parsing $file ...");
        my $orgp = Org::Parser->new;
        my $curtodo;
        $orgp->handler(
            sub {
                my ($orgp, $ev, $args) = @_;
                return unless $ev eq 'element';
                my $el      = $args->{element};
                my $is_hl   = $el->isa('Org::Element::Headline');
                return unless $is_hl && $el->is_todo && !$el->is_done
                    || $el->isa('Org::Element::Timestamp') && $el->is_active;
                if ($is_hl && $el->is_todo) {
                    $curtodo = $el;
                }

                return unless !$is_hl && $curtodo;
                my $days = int(($el->datetime->epoch-$today->epoch)/86400);
                if ($days <= $args{days_before}) {
                    push @res,
                        sprintf("%s: %s (%s)",
                                $days == 0 ? "today" :
                                    $days < 0 ? abs($days)." days ago" :
                                        "in $days days",
                                $curtodo->title->as_string,
                                $el->datetime->ymd);
                }
                $curtodo = undef;
            });
        $orgp->parse_file($file);
    }
    [200, "OK", \@res];
}

run(load=>0, module => 'remind_due_todos', sub=>'get_due_todos');

__END__
=pod

=head1 NAME

remind_due_todos

=head1 VERSION

version 0.05

=head1 AUTHOR

Steven Haryanto <stevenharyanto@gmail.com>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2011 by Steven Haryanto.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut