#!/usr/bin/perl

use LWP::UserAgent;
use JSON;
use Data::Dumper;
use utf8;

my $WOEID  = $ARGV[0];
my $APPID  = '<enter your appid here>';
my $YAHOO  = "http://where.yahooapis.com/v1/place/$WOEID?format=json&appid=$APPID";
my $FBASE  = "http://www.freebase.com/view/guid/";
my $WPDIA  = "http://en.wikipedia.org/wiki/index.html?curid=";
my $FBQRY  = "http://api.freebase.com/api/service/search";
my $DEBUG  = 0;

my $ua = LWP::UserAgent->new;

my $response = $ua->get($YAHOO);

mydie("Cannot connect to Yahoo API: ".$response->status_line) unless $response->is_success;
my $json = $response->decoded_content;
my $jsonobj = from_json($json);

my $placeName	= $$jsonobj{'place'}{'name'};
my $minLat	= $$jsonobj{'place'}{'boundingBox'}{'southWest'}{'latitude'};
my $minLon	= $$jsonobj{'place'}{'boundingBox'}{'southWest'}{'longitude'};
my $maxLat	= $$jsonobj{'place'}{'boundingBox'}{'northEast'}{'latitude'};
my $maxLon	= $$jsonobj{'place'}{'boundingBox'}{'northEast'}{'longitude'};

my $query = qq|$placeName&type=/location/citytown&prefixed=true&indent=1&limit=10&blacklist=fus&mql_output=[{"name":null,"key":{"namespace":"/wikipedia/en_id","value":null}}]&mql_filter=[{"type":"/location/location","geolocation":{"latitude>":$minLat,"latitude<":$maxLat,"longitude>":$minLon,"longitude<":$maxLon},"key":{"namespace":"/wikipedia/en_id","value":null}}]|;

my $FBURL = $FBQRY . "?query=" . $query;
print "FB URL: ".$FBURL."\n" if $DEBUG;
my $response = $ua->get($FBURL);

mydie("Cannot connect to Freebase: ".$response->status_line) unless $response->is_success;
$json = $response->decoded_content;
$jsonobj = from_json($json);

print $json if $DEBUG;

my $status = $$jsonobj{'status'};
print "$status\n" if $DEBUG;
if ($status =~ "200"){
	# if results array is empty then there is something not working here
	# (i.e. the coordinates passed by Yahoo are not consistent with the
	#  ones in freebase)
	my $topcity = $$jsonobj{'result'}[0];

	my %output;
	$output{'woeid'} = $WOEID;
	$output{'name'}  = $$topcity{'name'};
	$output{'wpURI'} = $WPDIA . $$topcity{'key'}{'value'};
	$output{'fbURI'} = $FBASE . substr $$topcity{'guid'}, 1;

	my $jsonOutput = new JSON;
	my $output_json = $jsonOutput->pretty->encode(\%output);
	utf8::encode($output_json);
	print $placeName."\n\n";
	print $output_json;
}else{
	# die or signal error
}


exit;

#----------------------------------------------------------------------------

sub mydie{
	my ($error) = @_;
	die "[x] $error\n";
}
