#!/usr/bin/env perl

# Simple program to look up and print the information on a given address.
#	e.g. "./address_lookup Fairfield Road, Broadstairs, Kent, UK"

use warnings;
use strict;
use autodie qw(:all);

use FindBin qw($Bin);
use Getopt::Std;
use lib "$Bin/../lib";
use Geo::Coder::Free;
use Geo::Coder::Free::Local;

if(scalar(@ARGV) == 0) {
	die "Usage: $0 location";
}

my %opts;
getopts('v', \%opts);
Geo::Coder::Free::DB::init(logger => MyLogger->new()) if($opts{'v'});

# print join(' ', @ARGV), "\n";
if(my $rc = Geo::Coder::Free::Local::geocode(join(' ', @ARGV))) {
	print 'Local: ', Data::Dumper->new([$rc])->Dump();
} elsif($rc = Geo::Coder::Free::geocode(join(' ', @ARGV))) {
# if(my $rc = Geo::Coder::Free::geocode(join(' ', @ARGV))) {
	print Data::Dumper->new([$rc])->Dump();
} elsif($ENV{'OPENADDR_HOME'} && ($rc = Geo::Coder::Free::OpenAddresses->new(openaddr => $ENV{'OPENADDR_HOME'})->geocode(location => join(' ', @ARGV)))) {
	print Data::Dumper->new([$rc])->Dump();
} else {
	exit(1);
}

package MyLogger;

use strict;
use warnings;

sub new {
	my ($proto, %args) = @_;

	my $class = ref($proto) || $proto;

	return bless { }, $class;
}

sub trace {
	debug(@_);
}

sub warn {
	debug(@_);
}

sub debug {
	my $self = shift;

	print @_, "\n";
}

sub AUTOLOAD {
	our $AUTOLOAD;
	my $param = $AUTOLOAD;

	unless($param eq 'MyLogger::DESTROY') {
		die "Need to define $param";
	}
}

1;
