#!/usr/bin/env ruby

require_relative 'database'
require_relative 'vocabularies'
require_relative 'migrants'

output = File.open(File.join('data', 'locations.ttl'), 'w')

output.puts prefixes(:wd, :rdfs, :skos, :schema, :tm, :country, :location, :region)
output.puts

# Define the regions

REGIONS = {
  'Africa' => {
    wikidata: 'wd:Q15'
  },
  'Asia' => {
    wikidata: 'wd:Q48'
  },
  'Australia' => {
    wikidata: 'wd:Q3960'
  },
  'East Asia' => {
    wikidata: 'wd:Q27231',
    part_of: 'Asia'
  },
  'Europe' => {
    wikidata: 'wd:Q46'
  },
  'Middle East' => {
    wikidata: 'wd:Q7204'
  },
  'North Africa' => {
    wikidata: 'wd:Q27381',
    part_of: 'Africa'
  },
  'North America' => {
    wikidata: 'wd:Q49'
  },
  'Oceania' => {
    wikidata: 'wd:Q538'
  },
  'South America' => {
    wikidata: 'wd:Q18'
  }
}

# Print the regions

REGIONS.each do |reg_name, reg_attr|
  reg_attr[:id] = "region:#{toName(reg_name)}"
  output.puts "#{reg_attr[:id]} a tm:Region ; skos:prefLabel \"#{reg_name}\"@en ."
end

output.puts

# Print locations

DB[:location].each do |location|
  id = location[:IDLocation]
  props = ["a tm:Location"]

  region = REGIONS[location[:Continent]]
  props << "tm:continent #{region[:id]}"                                  if region
  props << "tm:country country:#{toName(location[:Country])}"             unless location[:Country].to_s.empty?
  props << "tm:state #{ttl_literal(location[:State])}"                   unless location[:State].to_s.empty?
  props << "rdfs:label #{ttl_literal(location[:City])}"                  unless location[:City].to_s.empty?
  props << "schema:latitude #{ttl_literal(location[:latitude])}"         if location[:latitude]
  props << "schema:longitude #{ttl_literal(location[:longitude])}"       if location[:longitude]
  props << "schema:sameAs <#{location[:wikipedia]}>"                      unless location[:wikipedia].to_s.empty?
  props << "schema:sameAs wd:#{location[:wikidata]}"                     unless location[:wikidata].to_s.empty?
  props << "schema:sameAs <http://sws.geonames.org/#{location[:GeoNamesID]}/>" unless location[:GeoNamesID].to_s.empty?

  output.puts "location:#{id} #{props.first} ;"
  props[1..-2].each { |p| output.puts "  #{p} ;" }
  output.puts "  #{props.last} ."
  output.puts
end

output.close
