#!/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('vd', \%opts);
# Watch what's going on in debug mode
Database::Abstraction::init(logger => MyLogger->new()) if($opts{'d'});

print join(' ', @ARGV), ': ' if($opts{'v'});
if(my $rc = Geo::Coder::Free::Local::geocode(join(' ', @ARGV))) {
	print 'Local: ', Data::Dumper->new([$rc])->Dump();
} elsif($ENV{'OPENADDR_HOME'}) {
	if($rc = Geo::Coder::Free::OpenAddresses->new(openaddr => $ENV{'OPENADDR_HOME'})->geocode(location => join(' ', @ARGV), exact => 1)) {
		print Data::Dumper->new([$rc])->Dump();
	} elsif($rc = Geo::Coder::Free::MaxMind::geocode(join(' ', @ARGV))) {
		print Data::Dumper->new([$rc])->Dump();
	} else {
		print "Not found\n" if($opts{'v'});
		exit(1);
	}
} elsif($rc = Geo::Coder::Free::geocode(join(' ', @ARGV))) {
	print Data::Dumper->new([$rc])->Dump();
} else {
	print "Not found\n" if($opts{'v'});
	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;
