#!perl

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

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

our %SPEC;

$SPEC{download_bca} = {
    v => 1.1,
    summary => 'Download BCA statement',
    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::BCA constructor',
            schema=>'str*',
            default=>'',
        },
        days      => {schema=>'int*', default=>31},
    },
};
sub download_bca {
    require File::HomeDir;

    my %args = @_;

    my $data_dir = $args{data_dir} // File::HomeDir->my_home . "/bca";
    my $log_dir  = $args{log_dir}  // File::HomeDir->my_home . "/bca/logs";
    my $save_dir = $args{save_dir} // File::HomeDir->my_home . "/bca/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::BCA;
    my $ibank = Finance::Bank::ID::BCA->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_balances;
        $log->debug("Balances: ".$ibank->_dmp(\@bal));

        my $stmt = $ibank->get_statement(
            account    => $args{account},
            days       => $args{days},
            parse_opts => {return_datetime_obj=>0},
        );
        my $filename = sprintf("%s/bca.statement.%s.%s.to.%s.yaml",
                               $data_dir,
                               $stmt->{account},
                               $stmt->{start_date},
                               $stmt->{end_date});
        $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_bca',
    log_any_app => 0, # because we'll init ourselves inside download_bca()
)->run;

# ABSTRACT: Download BCA statement
# PODNAME: download-bca

__END__

=pod

=encoding UTF-8

=head1 NAME

download-bca - Download BCA statement

=head1 VERSION

This document describes version 0.33 of download-bca (from Perl distribution Finance-Bank-ID-BCA), released on 2015-02-06.

=head1 SYNOPSIS

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

 username=ABCDEF0123
 password=123456

Then:

 % download-bca

Or, if you want to store multiple profiles in the configuration:

 [jajang]
 username=jajang0123
 password=123456

 [saidah]
 username=saidah0123
 password=123456

Then:

 % download-bca --config-profile jajang

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

=head1 DESCRIPTION

This is a command-line script which you can run from cron or whatever to
conveniently download BCA statements. By default, it downloads 31 day's worth of
statements to C<~/bca/>. To change this, use C<--days> and C<--data-dir>
options.

=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::BCA 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_BCA_OPT

=head1 FILES

~/download-bca.conf

/etc/download-bca.conf

=head1 SEE ALSO

L<Finance::Bank::ID::BCA>

=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-bca download-bca

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-bca 'p/*/`download-bca`/'

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-BCA>.

=head1 SOURCE

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

=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-BCA>

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
