use strict;
use warnings;
use vars '$VERSION';

$VERSION = '0.02';

use Getopt::Std;

use lib 'blib/lib';
use WWW::Velib;

getopts( 'a:c:eLl:m:p:', \my %opt );

my ($login, $pin, $cache);

if ($opt{e}) {
    $login = $ENV{VELIB_LOGIN};
    $pin   = $ENV{VELIB_PIN};
}
exists $opt{l} and $login = $opt{l};
exists $opt{p} and $pin   = $opt{p};

my %arg;

if (defined $login and defined $pin) {
    $arg{login} = $login;
    $arg{pin}   = $pin;
}
else {
    $arg{defer} = 1;
}

exists $opt{a} and $arg{myaccount} = $opt{a};
exists $opt{c} and $arg{cache_dir} = $opt{c};

exists $opt{a} and $arg{myaccount} = ($opt{c} ? "$opt{c}/" : '') . $opt{a};
exists $opt{m} and $arg{month}     = ($opt{c} ? "$opt{c}/" : '') . $opt{m};

if ($opt{L} and $arg{cache_dir}) {
    my $dir = $arg{cache_dir};
    opendir D, $dir or die "Cannot open directory $dir: $!\n";
    my $month_epoch = 0;
    my $acct_epoch = 0;
    while (defined(my $entry = readdir D)) {
        next if $entry eq '.' or $entry eq '..';
        if ($entry =~ /^month\./) {
            my $file = "$dir/$entry";
            my $mtime = (stat $file)[9];
            if ($month_epoch < $mtime) {
                $month_epoch = $mtime;
                $arg{month} = $file;
            }
        }
        elsif ($entry =~ /^myaccount\./) {
            my $file = "$dir/$entry";
            my $mtime = (stat $file)[9];
            if ($acct_epoch < $mtime) {
                $acct_epoch = $mtime;
                $arg{myaccount} = $file;
            }
        }
    }
    closedir D;
}

my $v = WWW::Velib->new(%arg);
$v->get_month unless $arg{defer};

if ($opt{b}) {
    print $v->conso_bal, "\n";
    exit;
}

print
    'end_date    = ', $v->end_date, "\n",
    'remain      = ', $v->remain, "\n",
    'in use      = ', $v->in_use, "\n",
    'conso_bal   = ', $v->conso_bal,  " (balance = ", $v->balance, ")\n",
    'conso_month = ', $v->conso_month, "\n",
    'conso_year  = ', $v->conso_year, "\n",
    'conso_trips = ', $v->conso_trips, "\n",
    'conso_time  = ', $v->conso_time, "\n",
;

for my $trip ($v->trips) {
    print "$trip->{date} $trip->{duration}m from $trip->{from} to $trip->{to}\n";
}
