package App::DateUtils;

our $DATE = '2015-09-23'; # DATE
our $VERSION = '0.02'; # VERSION

use 5.010001;
use strict;
use warnings;

our %SPEC;

my %time_zone_arg = (
    time_zone => {
        schema => 'str*',
        cmdline_aliases => {timezone=>{}},
    },
);

my %dates_arg = (
    dates => {
        schema => ['array*', of=>'str*', min_len=>1],
        'x.name.is_plural' => 1,
        req => 1,
        pos => 0,
        greedy => 1,
    },
);

my %durations_arg = (
    durations => {
        schema => ['array*', of=>'str*', min_len=>1],
        'x.name.is_plural' => 1,
        req => 1,
        pos => 0,
        greedy => 1,
    },
);

$SPEC{parse_date} = {
    v => 1.1,
    summary => 'Parse date string(s) using one of several modules',
    args => {
        module => {
            schema  => ['str*', in=>[
                'DateTime::Format::Alami::EN',
                'DateTime::Format::Alami::ID',
                'DateTime::Format::Natural',
            ]],
            default => 'DateTime::Format::Natural',
            cmdline_aliases => {m=>{}},
        },
        %time_zone_arg,
        %dates_arg,
    },
    examples => [
        {
            argv => ['23 sep 2015','tomorrow','foo'],
        },
    ],
};
sub parse_date {
    my %args = @_;

    my $mod = $args{module};

    my $parser;
    if ($mod eq 'DateTime::Format::Alami::EN') {
        require DateTime::Format::Alami::EN;
        $parser = DateTime::Format::Alami::EN->new(
            ( time_zone => $args{time_zone} ) x !!(defined($args{time_zone})),
        );
    } elsif ($mod eq 'DateTime::Format::Alami::ID') {
        require DateTime::Format::Alami::ID;
        $parser = DateTime::Format::Alami::ID->new(
            ( time_zone => $args{time_zone} ) x !!(defined($args{time_zone})),
        );
    } elsif ($mod eq 'DateTime::Format::Natural') {
        require DateTime::Format::Natural;
        $parser = DateTime::Format::Natural->new(
            ( time_zone => $args{time_zone} ) x !!(defined($args{time_zone})),
        );
    }

    my @res;
    for my $date (@{ $args{dates} }) {
        my $rec = { original => $date };
        if ($mod =~ /^DateTime::Format::(Alami|Natural)/) {
            my $dt = $parser->parse_datetime($date);
            my $success = $mod =~ /Alami/ ? $dt : $parser->success;

            if ($success) {
                $rec->{is_parseable} = 1;
                $rec->{as_epoch} = $dt->epoch;
                $rec->{as_datetime_obj} = "$dt";
            } else {
                $rec->{is_parseable} = 0;
            }
        }
        push @res, $rec;
    }
    [200, "OK", \@res];
}

$SPEC{parse_date_using_df_natural} = {
    v => 1.1,
    summary => 'Parse date string(s) using DateTime::Format::Natural',
    args => {
        %time_zone_arg,
        %dates_arg,
    },
};
sub parse_date_using_df_natural {
    my %args = @_;
    parse_date(module=>'DateTime::Format::Natural', %args);
}

$SPEC{parse_duration} = {
    v => 1.1,
    summary => 'Parse duration string(s) using one of several modules',
    args => {
        module => {
            schema  => ['str*', in=>[
                'DateTime::Format::Duration',
                'Time::Duration::Parse',
            ]],
            default => 'Time::Duration::Parse',
            cmdline_aliases => {m=>{}},
        },
        %durations_arg,
    },
};
sub parse_duration {
    my %args = @_;

    my $mod = $args{module};

    my $parser;
    if ($mod eq 'DateTime::Format::Duration') {
        require DateTime::Format::Duration;
        $parser = DateTime::Format::Duration->new(
        );
    } elsif ($mod eq 'Time::Duration::Parse') {
        require Time::Duration::Parse;
    }

    my @res;
    for my $dur (@{ $args{durations} }) {
        my $rec = { original => $dur };
        if ($mod eq 'DateTime::Format::Duration') {
            my $dtdur = $parser->parse_duration($dur);
            if ($dtdur) {
                $rec->{is_parseable} = 1;
                $rec->{as_dtdur_obj} = "$dtdur";
                $rec->{as_secs} = $dtdur->in_units('seconds');
            } else {
                $rec->{is_parseable} = 0;
            }
        } elsif ($mod eq 'Time::Duration::Parse') {
            my $secs;
            eval { $secs = Time::Duration::Parse::parse_duration($dur) };
            if ($@) {
                $rec->{is_parseable} = 0;
                $rec->{error_msg} = $@;
                $rec->{error_msg} =~ s/\n+/ /g;
            } else {
                $rec->{is_parseable} = 1;
                $rec->{as_secs} = $secs;
            }
        }
        push @res, $rec;
    }
    [200, "OK", \@res];
}

$SPEC{parse_duration_using_df_duration} = {
    v => 1.1,
    summary => 'Parse date string(s) using DateTime::Format::Duration',
    args => {
        %durations_arg,
    },
};
sub parse_duration_using_df_duration {
    my %args = @_;
    parse_duration(module=>'DateTime::Format::Duration', %args);
}

1;
# ABSTRACT: An assortment of date-/time-related CLI utilities

__END__

=pod

=encoding UTF-8

=head1 NAME

App::DateUtils - An assortment of date-/time-related CLI utilities

=head1 VERSION

This document describes version 0.02 of App::DateUtils (from Perl distribution App-DateUtils), released on 2015-09-23.

=head1 SYNOPSIS

This distribution provides the following command-line utilities related to
date/time:

=over

=item * L<parse-date>

=item * L<parse-date-using-df-natural>

=item * L<parse-duration>

=item * L<parse-duration-using-df-duration>

=back

=head1 SEE ALSO

L<App::datecalc>

=head1 FUNCTIONS


=head2 parse_date(%args) -> [status, msg, result, meta]

Parse date string(s) using one of several modules.

Examples:

 parse_date( dates => ["23 sep 2015", "tomorrow", "foo"]);


Result:

 [
   200,
   "OK",
   [
     {
       as_datetime_obj => "2015-09-23T00:00:00",
       as_epoch        => 1442966400,
       is_parseable    => 1,
       original        => "23 sep 2015",
     },
     {
       as_datetime_obj => "2015-09-24T00:00:00",
       as_epoch        => 1443052800,
       is_parseable    => 1,
       original        => "tomorrow",
     },
     { is_parseable => 0, original => "foo" },
   ],
 ]


Arguments ('*' denotes required arguments):

=over 4

=item * B<dates>* => I<array[str]>

=item * B<module> => I<str> (default: "DateTime::Format::Natural")

=item * B<time_zone> => I<str>

=back

Returns an enveloped result (an array).

First element (status) is an integer containing HTTP status code
(200 means OK, 4xx caller error, 5xx function error). Second element
(msg) is a string containing error message, or 'OK' if status is
200. Third element (result) is optional, the actual result. Fourth
element (meta) is called result metadata and is optional, a hash
that contains extra information.

Return value:  (any)


=head2 parse_date_using_df_natural(%args) -> [status, msg, result, meta]

Parse date string(s) using DateTime::Format::Natural.

Arguments ('*' denotes required arguments):

=over 4

=item * B<dates>* => I<array[str]>

=item * B<time_zone> => I<str>

=back

Returns an enveloped result (an array).

First element (status) is an integer containing HTTP status code
(200 means OK, 4xx caller error, 5xx function error). Second element
(msg) is a string containing error message, or 'OK' if status is
200. Third element (result) is optional, the actual result. Fourth
element (meta) is called result metadata and is optional, a hash
that contains extra information.

Return value:  (any)


=head2 parse_duration(%args) -> [status, msg, result, meta]

Parse duration string(s) using one of several modules.

Arguments ('*' denotes required arguments):

=over 4

=item * B<durations>* => I<array[str]>

=item * B<module> => I<str> (default: "Time::Duration::Parse")

=back

Returns an enveloped result (an array).

First element (status) is an integer containing HTTP status code
(200 means OK, 4xx caller error, 5xx function error). Second element
(msg) is a string containing error message, or 'OK' if status is
200. Third element (result) is optional, the actual result. Fourth
element (meta) is called result metadata and is optional, a hash
that contains extra information.

Return value:  (any)


=head2 parse_duration_using_df_duration(%args) -> [status, msg, result, meta]

Parse date string(s) using DateTime::Format::Duration.

Arguments ('*' denotes required arguments):

=over 4

=item * B<durations>* => I<array[str]>

=back

Returns an enveloped result (an array).

First element (status) is an integer containing HTTP status code
(200 means OK, 4xx caller error, 5xx function error). Second element
(msg) is a string containing error message, or 'OK' if status is
200. Third element (result) is optional, the actual result. Fourth
element (meta) is called result metadata and is optional, a hash
that contains extra information.

Return value:  (any)

=head1 HOMEPAGE

Please visit the project's homepage at L<https://metacpan.org/release/App-DateUtils>.

=head1 SOURCE

Source repository is at L<https://github.com/perlancar/perl-App-DateUtils>.

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website L<https://rt.cpan.org/Public/Dist/Display.html?Name=App-DateUtils>

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=head1 AUTHOR

perlancar <perlancar@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2015 by perlancar@cpan.org.

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
