#!perl

our $DATE = '2014-08-26'; # DATE
our $VERSION = '0.29'; # VERSION

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

our %SPEC;

$SPEC{download_mandiri} = {
    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::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;
Perinci::CmdLine->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.29 of download-mandiri (from Perl distribution Finance-Bank-ID-Mandiri), released on 2014-08-26.

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

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

=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/sharyanto/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

Steven Haryanto <stevenharyanto@gmail.com>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2014 by Steven Haryanto.

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
