#!perl

our $DATE = '2014-09-09'; # DATE
our $VERSION = '0.31'; # VERSION

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

our %SPEC;

$SPEC{download_bca} = {
    v => 1.1,
    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;
Perinci::CmdLine->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.31 of download-bca (from Perl distribution Finance-Bank-ID-BCA), released on 2014-09-09.

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

 [steven]
 username=steven0123
 password=123456

 [rudi]
 username=rudito0123
 password=123456

Then:

 % download-bca --config-profile steven

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 SEE ALSO

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

=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) 2014 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
