#!perl

our $DATE = '2015-02-06'; # DATE
our $VERSION = '0.31'; # VERSION

use 5.010;
use strict;
use warnings;
use Log::Any '$log';

our %SPEC;

$SPEC{download_mandiri} = {
    v => 1.1,
    summary => 'Download Mandiri statements',
    args => {
        username  => {schema=>'str*', req=>1},
        password  => {schema=>'str*', req=>1},
        account   => {schema=>'str*'},
        data_dir  => {schema=>'str*'},
        log_dir   => {schema=>'str*'},
        save_dir  => {schema=>'str*'},
        mode      => {
            summary=>'Passed to Finance::Bank::ID::Mandiri constructor',
            schema=>'str*',
            default=>'',
        },
        days      => {schema=>'int*', default=>31},
    },
};

sub download_mandiri {
    require File::HomeDir;

    my %args = @_;

    my $data_dir = $args{data_dir} // File::HomeDir->my_home . "/mandiri";
    my $log_dir  = $args{log_dir}  // File::HomeDir->my_home . "/mandiri/logs";
    my $save_dir = $args{save_dir} // File::HomeDir->my_home . "/mandiri/logs/save";

    local $ENV{SCREEN_LOG_LEVEL} = 'debug'
        if (-t STDOUT) && !$ENV{SCREEN_LOG_LEVEL};
    require Log::Any::App;
    Log::Any::App::init([
        -category_level => {Dumps=>'off'},
        -file           => {
            path           => "$log_dir/main.log",
        },
        -dir            => {
            path           => "$log_dir/dumps",
            level          => 'off',
            # currently we always dump, Log::Any::App > 0.23 will support
            # specifying sub { ... } to refer to general level
            category_level => {Dumps => 'trace'},
        },
    ]);

    require File::Path;
    File::Path::mkpath($data_dir) unless -d $data_dir;
    die "Can't create data_dir `$data_dir'" unless -d $data_dir;

    $log->info("Start session");

    require Finance::Bank::ID::Mandiri;
    my $ibank = Finance::Bank::ID::Mandiri->new(
        username     => $args{username},
        password     => $args{password},
        logger       => $log,
        logger_dump  => Log::Any->get_logger(category => "Dumps"),
        verify_https => 1,
        save_dir     => $save_dir,
        mode         => $args{mode},
    );

    eval {
        my $bal = $ibank->check_balance;
        $log->debug("Balance: $bal");

        my $stmt = $ibank->get_statement(
            account    => $args{account},
            days       => $args{days},
            parse_opts => {return_datetime_obj=>0},
        );
        my $filename = sprintf("%s/mandiri.statement.%s.%s.to.%s.yaml",
                               $data_dir,
                               $stmt->{account},
                               $stmt->{start_date},
                               $stmt->{end_date});

        # insert balance to statement (since mandiri statement doesn't contain
        # any balance information)
        $stmt->{_balance} = $bal;

        $filename =~ s/[: ]//g; # : is for windows
        $log->info("Writing statements to YAML file `$filename' ...");
        require File::Slurp::Tiny;
        require YAML::Syck;
        File::Slurp::Tiny::write_file($filename, YAML::Syck::Dump($stmt));
    };

    if ($@) {
        $log->error("die: $@");
    }

    # no matter what, try to logout so we're not locked out for 10 minutes,
    # annoying
    eval { $ibank->logout };

    $log->info("End session");
    [200];
}

require Perinci::CmdLine::Classic;
Perinci::CmdLine::Classic->new(
    url => '/main/download_mandiri',
    log_any_app => 0, # because we'll init ourselves inside download_mandiri()
)->run;

# ABSTRACT: Download Mandiri statements
# PODNAME: download-mandiri

__END__

=pod

=encoding UTF-8

=head1 NAME

download-mandiri - Download Mandiri statements

=head1 VERSION

This document describes version 0.31 of download-mandiri (from Perl distribution Finance-Bank-ID-Mandiri), released on 2015-02-06.

=head1 SYNOPSIS

First, put your username and password in C<~/download-mandiri.conf>, e.g.:

 username = ABCDEF0123
 password = 123456

Then:

 % download-mandiri

Get your statements in data dir (defaults to C<~/mandiri/>). See logs in your
log dir (defaults to C<~/mandiri/logs>).

=head1 DESCRIPTION

This is a command-line script which you can run from cron or whatever to
conveniently download Bank Mandiri statements. By default, it downloads 1
month's worth of statements to C<~/mandiri/>. To change this, use C<--days> and
C<--data_dir>.

=head1 OPTIONS

C<*> marks required options.

=over

=item B<--account>=I<s>

=item B<--config-path>=I<s>

{en_US Set path to configuration file}.

Can be specified multiple times.

=item B<--config-profile>=I<s>

{en_US Set configuration profile to use}.

=item B<--data-dir>=I<s>

=item B<--days>=I<i>

Default value:

 31

=item B<--format-options>=I<s>

{en_US Pass options to formatter}.

=item B<--format>=I<s>

{en_US Choose output format, e.g. json, text}.

=item B<--help>, B<-h>, B<-?>

{en_US Display this help message}.

=item B<--json>

{en_US Equivalent to --format=json-pretty}.

=item B<--log-dir>=I<s>

=item B<--mode>=I<s>

{en_US Passed to Finance::Bank::ID::Mandiri constructor}.

Default value:

 ""

=item B<--no-config>

{en_US Do not use any configuration file}.

=item B<--password>=I<s>*

=item B<--save-dir>=I<s>

=item B<--username>=I<s>*

=item B<--version>, B<-v>

=back

=head1 ENVIRONMENT

DOWNLOAD_MANDIRI_OPT

=head1 FILES

~/download-mandiri.conf

/etc/download-mandiri.conf

=head1 SEE ALSO

L<Finance::Bank::ID::Mandiri>

=head1 COMPLETION

This script has shell tab completion capability with support for several shells.

=head2 bash

To activate bash completion for this script, put:

 complete -C download-mandiri download-mandiri

in your bash startup (e.g. C<~/.bashrc>). Your next shell session will then recognize tab completion for the command. Or, you can also directly execute the line above in your shell to activate immediately.

It is recommended, however, that you install L<shcompgen> which allows you to activate completion scripts for several kinds of scripts on multiple shells. Some CPAN distributions (those that are built with L<Dist::Zilla::Plugin::GenShellCompletion>) will even automatically enable shell completion for their included scripts (using C<shcompgen>) at installation time, so you can immadiately have tab completion.

=head2 tcsh

To activate tcsh completion for this script, put:

 complete download-mandiri 'p/*/`download-mandiri`/'

in your tcsh startup (e.g. C<~/.tcshrc>). Your next shell session will then recognize tab completion for the command. Or, you can also directly execute the line above in your shell to activate immediately.

It is also recommended to install C<shcompgen> (see above).

=head2 other shells

For fish and zsh, install C<shcompgen> as described above.

=head1 HOMEPAGE

Please visit the project's homepage at L<https://metacpan.org/release/Finance-Bank-ID-Mandiri>.

=head1 SOURCE

Source repository is at L<https://github.com/perlancar/perl-Finance-Bank-ID-Mandiri>.

=head1 BUGS

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

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
