#!/usr/bin/perl
use strict;
use LWP;
use JSON;
use HTTP::Request::Common qw(GET POST);
use vars qw();

# XXX WARNING: only a sample; please do NOT hard-code your username 
# or passwords in this manner in your API clients

my $username = "username";   
my $password = "password"; 

#############

sub checkError {
    my $response = shift;

    if (not defined $response) {
        die ("error while sending request: $!");
    }

    my $hashref = decode_json ($response->content);
    if ($hashref->{response}->{status} ne "OK") { 
        my $message = $hashref->{response}->{status};
        $message =~ s/ERROR://;
        die ("Buxfer reported an error: $message");
    }

    return $hashref->{response};
}

my $base = "https://www.buxfer.com/api";
my $user_agent = new LWP::UserAgent ();

my $url = "$base/login?userid=$username&password=$password";
my $response = checkError ($user_agent->request (GET $url));
my $token = $response->{token};
my $url = "$base/budgets.json&token=$token";
my $response = checkError ($user_agent->request (GET $url));

foreach (@{$response->{budgets}}) { 
    my $budget = $_;
    print sprintf ("%12s %8s %10.2f %10.2f\n", $budget->{name}, $budget->{currentPeriod}, $budget->{limit}, $budget->{remaining});
}

exit (0);
