#!/usr/bin/env ruby
# coding: utf-8
# Create uMap-format GeoJSON correction from Loremap DB

require 'sqlite3'
require 'json'
require 'csv'

# Test1: extract by maptype:
# Usage: ./vdb2umap.rb tourist
#	Create .umap file of "tourist" theme

ARGV[0]==nil and abort "Specify MAPTYPE.  eg) #{$0} tourist"
mtype = ARGV[0]

mapdb = SQLite3::Database.new("db/viewer_prc.sq3")
mapdb.results_as_hash = true

# ename|name|addr|lat|lon|maptype|attr|value|objtype|jsonval

r = mapdb.execute(<<-EOF, mtype)
	SELECT ename, name, addr, lat, lon, value as Desc, objtype, jsonval
	FROM mapitem NATURAL JOIN object NATURAL JOIN attribute
	WHERE ename IN (SELECT ename FROM maptype WHERE maptype=?)
	  AND attr='description'
	EOF
if r.empty? then
  exit 0
end

umap = {
  'type'	=> 'umap-mimic',
  'properties'	=> {'description' => 'Generated from vdb2umap'},
  'geometry'	=> {
    "type" => "Point",
    "coordinates" => [139.82866287231448, 38.89744587262311]
  },
}
layers = {}
featurehash = {}
layerdelimRX = /^layer\[(.*?)\]=/m
defaultlayer = "Deafault"
r.each do |ent|
  # ename, name, addr, lat, lon, Desc, objtype, jsonval
  d = ent['Desc']
  featurebase = {
    'ename'	=> ent['ename'],		# unnecessary
    'type'	=> 'Feature',
    'geometry'	=> {
      'type'		=> 'Point',		# Support only Point now...
      'coordinates'	=> [ent['lon'].to_f, ent['lat'].to_f]
    },
    'properties'=>   {}
  }
  propbase = {
      'name'		=> ent['name'],
      ## 'description'	=> d,
  }
  # Check additional layer description
  # printf("%s(desc) = %s\n", ent['name'], d)
  deschash = {'description' => d}
  if layerdelimRX =~ d
    while layerdelimRX =~ d			# Hmm, scan() cannot be used
      d, layer = $', $1
      #layers[layer] = d.sub(layerdelimRX, "")	# extract layer name and desc
      layers[layer] ||= {
        "type"		=> "FeatureCollection",
        "features"	=> []
      }
      feature = featurebase.merge({
	'properties' => propbase.merge({'description' => d.split(layerdelimRX)[0]})
      })
      layers[layer]["features"] << feature
    end
  else
    layers[defaultlayer] ||= {
      "type"		=> "FeatureCollection",
      "features"	=> []
    }
    feature = featurebase.merge({
      'properties' => propbase.merge({'description' => d})
    })
    layers[defaultlayer]["features"] << feature
  end
end

umaplayers = []
layers.each do |name, ly|
  umaplayers << ly.merge({"_umap_options" => {"name" => name}})
end
umap['layers'] = umaplayers
print JSON.pretty_generate(umap)
