#!/usr/bin/perl -w
package ExchangeRate;

use LWP::UserAgent;
use POSIX;
use HTML::TokeParser;

use strict;

my $ua;

sub new {
    my $self = shift;

    my $ua = new LWP::UserAgent;
    $ua->agent( "ExchangeRate/0.1 " . $ua->agent );
    $ua->env_proxy();

    my $obj = bless {}, $self;

    $obj->{'ua'} = $ua;

    $obj;
}

sub convert {
    my $self = shift;
    my ( $frm, $amt, $to ) = @_;
    $to ||= "EUR";
    $amt ||= 1;

    if ( !defined( $frm )) {
        die "Usage: $0 FROM [ AMT [ TO ]]";
    }

    # Get a rate to convert with.
    my $req = new HTTP::Request
        GET => "http://www.google.com/search?q=$amt+$frm+in+$to&btnG=Search";
    print STDERR $req->as_string . "\n" if $ENV{DEBUG};
    my $res = $self->{ua}->request( $req );

    # Check the outcome of the response
    if ( $res->is_success ) {
        # Yay!
        my $page = $res->content;
        my $parser = new HTML::TokeParser( \$page );
        my $found = 0;

        while ( my $tag = $parser->get_tag( "td" )) {
            my $t = $parser->get_trimmed_text( "/td" );
            if ( $t =~ /$amt\s+.*?=\s+([0-9.]+)\s+/ ) {
                $amt = $1;
                $found = 1;
                last;
            }
        }

        die "Can't find rate" unless $found;

        return $amt;
    } else {
        die "Page error: " . $res->message . "\n";
    }
}

1;

