#!/bin/perl

use LWP::Simple;
use JSON;

use strict;
use warnings;
use utf8;

my $woonplaats="Gouda";
my $woonplaatscode=1005;  # BAG
my $liesin_uri_label_1="http://www.gemeentegeschiedenis.nl/gemeentenaam/Gouda Gouda";
my $liesin_uri_label_2="https://sws.geonames.org/2755419 Gouda";

my $debug=1;

my @wegenIDs=zoekWegen($woonplaats);

# header
print "dcterms:identifier\tskos:prefLabel\towl:sameAs\towl:sameAs\t";
print "hg:liesIn\thg:liesIn\twgs:long\twgs:lat\tasWKT\n";

# rows

foreach my $wegId (@wegenIDs) {
	my $weg=getWeg($wegId);

	if ($weg->{"type"} eq "weg" && $weg->{"woonplaatscode"} eq $woonplaatscode) {
				
		# "straat/"&SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(REGEXREPLACE(lower(B2),"\.$","")," ","-"),".","-"),"--","-"),"'",""),"é","e"),"ö","o"),"è","e")
		
		my $dcterms_identifier="straat/".lc($weg->{"straatnaam"});
		
		$dcterms_identifier=~s/\.$//;
		$dcterms_identifier=~s/[éèëê]/e/;
		$dcterms_identifier=~s/[óòöô]/o/;
		$dcterms_identifier=~s/'//;
		$dcterms_identifier=~s/[\.\s]/-/;
		$dcterms_identifier=~s/\-\-/-/;

		my $owl_sameAs_1="";
		my $wd_uri=getWikidata($weg->{"rdf_seealso"});
		if ($wd_uri) { 
			# uri label
			# uri = http://www.wikidata.org/entity/Q18927114
			# label = Wikidata Q108429495
			my ($wd_id)=($wd_uri=~/entity\/(Q[0-9]+)$/);
			my $wd_label="Wikidata ".$wd_id;
			$owl_sameAs_1=$wd_uri." ".$wd_label;
		}

		my $owl_sameAs_2;
		# uri label
		# uri = http://bag.basisregistraties.overheid.nl/bag/id/openbare-ruimte/0513300000000011
		# label = BAG id 0513300000000011
		my ($bag_id)=($weg->{"rdf_seealso"}=~/ruimte\/([0-9]+)$/);
		my $bag_label="BAG id ".$bag_id;
		$owl_sameAs_2=$weg->{"rdf_seealso"}." ".$bag_label;

		my $hg_liesIn_1=$liesin_uri_label_1;
		my $hg_liesIn_2=$liesin_uri_label_2;

		my $skos_prefLabel=$weg->{"straatnaam"}; # "Westhaven"
		print STDERR "- $skos_prefLabel\n";
		
		# POINT(4.71209255 52.00867368)
		my ($wgs_long,$wgs_lat)=($weg->{"centroide_ll"}=~m/\(([0-9\.]+) ([0-9\.]+)\)/);

		# MULTILINESTRING((4.71016 52.01021,4.71157 52.00926,4.71338 52.00725,4.71336 52.00695))
		
		my $asWKT=$weg->{"geometrie_ll"};

		print "$dcterms_identifier\t$skos_prefLabel\t$owl_sameAs_1\t$owl_sameAs_2\t";
		print "$hg_liesIn_1\t$hg_liesIn_2\t$wgs_long\t$wgs_lat\t$asWKT\n";

	}
}


sub zoekWegen {
	my ($plaats)=@_;
	
	my $start=0;
	my $rows=50;
	my @wegenIds;

	my $numFound;
	
	do {
		my $lookupAPI="https://geodata.nationaalgeoregister.nl/locatieserver/v3/suggest?q=".$plaats."&rows=".$rows."&fq=type:weg&start=".$start;
		print STDERR $lookupAPI."\n" if $debug;
		my $contents=get($lookupAPI);	sleep(1);
		my $data=decode_json $contents;
		$numFound=$data->{"response"}->{"numFound"};
		my @wegen=@{$data->{"response"}->{"docs"}};
		foreach my $weg (@wegen) {
			push(@wegenIds,$weg->{id});
		}
		$start+=$rows;
	} until ($numFound<$start);

	return @wegenIds;
}


sub getWeg {
	my ($wegId)=@_;

	my $fl="straatnaam,bron,type,woonplaatscode,rdf_seealso,weergavenaam,geometrie_ll,centroide_ll"; # of *
	my $lookupAPI="https://geodata.nationaalgeoregister.nl/locatieserver/v3/lookup?fl=".$fl."&id=".$wegId;
	print STDERR $lookupAPI."\n" if $debug;
	my $contents=get($lookupAPI);	sleep(1);
	my $data=decode_json $contents;
	my $weg=$data->{"response"}->{"docs"}[0];
	return $weg;
	
}



sub getWikidata {
	my ($bagId)=@_;

	$bagId=~s/https?\:\/\/bag\.basisregistraties\.overheid\.nl\/bag\/id\/openbare\-ruimte\///;
	my $lookupAPI="https://query.wikidata.org/sparql?query=SELECT%20%3Fstreet%20%3Fname%0AWHERE%0A%7B%0A%20%20%20%20%3Fstreet%20wdt%3AP31%20wd%3AQ79007%20.%0A%20%20%20%20%3Fstreet%20wdt%3AP6375%20%3Fname%20.%0A%20%20%20%20%3Fstreet%20wdt%3AP5207%20%22".$bagId."%22%0A%7D";
	print STDERR $lookupAPI."\n" if $debug;
	
	my $contents=get($lookupAPI);

	my ($wd)=($contents=~m/\<binding name=\'street\'\>\s*\<uri\>(.*?)\<\/uri\>\s*\<\/binding\>/s);
	# http://www.wikidata.org/entity/Q19650905

	return $wd;
	
}