#!/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://rdf.freebase.com/ns/";
my $SPARQL = "http://dbpedia.org/sparql/";
my $DEBUG  = 1;

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 $minLong	= $$jsonobj{'place'}{'boundingBox'}{'southWest'}{'longitude'};
my $maxLat	= $$jsonobj{'place'}{'boundingBox'}{'northEast'}{'latitude'};
my $maxLong	= $$jsonobj{'place'}{'boundingBox'}{'northEast'}{'longitude'};

my $query = <<EOT;
SELECT DISTINCT ?page ?fbase WHERE {
  ?city a <http://dbpedia.org/ontology/Place> .
  ?city foaf:page ?page .
  ?city <http://www.w3.org/2003/01/geo/wgs84_pos#lat> ?lat .
  ?city <http://www.w3.org/2003/01/geo/wgs84_pos#long> ?long .
  ?city rdfs:label ?label .
  ?city owl:sameAs ?fbase .
  FILTER (?lat > "$minLat"^^xsd:float) .
  FILTER (?lat < "$maxLat"^^xsd:float) .
  FILTER (?long > "$minLong"^^xsd:float) .
  FILTER (?long < "$maxLong"^^xsd:float) .
  FILTER (regex(str(?label), "^$placeName(\$|,.*)")) .
  FILTER (regex(?fbase, "$FBASE")) .
} 
EOT

print "$query\n" if $DEBUG;

$response = $ua->post($SPARQL,[
		"query" => $query, 
		"format" => "json"
	]);

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

my $bindings = $$jsonobj{'results'}{'bindings'};
my $size = @$bindings;

if ($size == 0){
	print "Got no bindings:\n$json\n";
}
if ($size >1){
	print "Got more than 1 binding:\n$json\n";
}else{
	my %output;
	$output{'woeid'} = $WOEID;
	$output{'wpURI'} = $$bindings[0]{'page'}{'value'};
	$output{'fbURI'} = $$bindings[0]{'fbase'}{'value'};

	my $jsonOutput = new JSON;
	my $output_json = $jsonOutput->pretty->encode(\%output);
	utf8::encode($output_json);
	print $output_json;
}

exit;

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

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