#!perl

our $DATE = '2014-12-10'; # DATE
our $VERSION = '0.32'; # 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.32 of download-bca (from Perl distribution Finance-Bank-ID-BCA), released on 2014-12-10.

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

You can also install L<App::BashCompletionProg> which makes it easy to add completion for Getopt::Long::Complete-based scripts. After you install the module and put C<. ~/.bash-complete-prog> (or C<. /etc/bash-complete-prog>), you can just run C<bash-completion-prog> and the C<complete> command will be added to your C<~/.bash-completion-prog>. Your next shell session will then recognize tab completion for the command.

=head2 fish

To activate fish completion for this script, execute:

 begin; set -lx COMP_SHELL fish; set -lx COMP_MODE gen_command; download-bca; end > $HOME/.config/fish/completions/download-bca.fish

Or if you want to install globally, you can instead write the generated script to C</etc/fish/completions/download-bca.fish> or C</usr/share/fish/completions/download-bca.fish>. The exact path might be different on your system. Please check your C<fish_complete_path> variable.

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

=head2 zsh

To activate zsh completion for this script, put:

 _download_bca() { read -l; local cl="$REPLY"; read -ln; local cp="$REPLY"; reply=(`COMP_SHELL=zsh COMP_LINE="$cl" COMP_POINT="$cp" download-bca`) }

 compctl -K _download_bca download-bca

in your zsh startup (e.g. C<~/.zshrc>). 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.

=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
