#!/usr/bin/env ruby
# coding: utf-8
# Convert uMap-format GeoJSON to DB

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

mydir	= File.dirname($0)
sq3	= ENV["DBFILE"] || File.expand_path("db/viewer_prc.sq3")

maptype	= "misc"

while /^-([a-z])/i =~ ARGV[0]
  ARGV.shift
  case $1
  when "t"		# Type of map
    maptype = ARGV.shift
  when "d"		# Database file
    sq3	= ARGV.shift
  end
end

db = SQLite3::Database.new(sq3)
db.results_as_hash = true

# Check if specified maptype availability
r = db.execute("SELECT mapname FROM mapname WHERE maptype=?", maptype)
if r.empty? || r[0].empty?
  $stderr.printf("Maptype [%s] is not in Database.  Continue?: ", maptype)
  /y/i =~ gets or abort "Ceased."
end

count = 0
db.transaction do
  ARGV.each do |js|
    d = JSON.parse(open(js){|j| j.read.toutf8})
    # If bare GeoJSON, fake umap first.
    um = (d["layers"] ? d : {"layers" => [d]})
    um["layers"].each do |ly|
      ly["features"].each do |f|
        prop	= f["properties"]
        geom	= f["geometry"]
        # We need : ename|name|addr|lat|lon|maptype|attr|value|objtype|jsonval
        ename	= "point-%03d" % (count+=1)
        name	= prop["name"] || prop["名称"] || ename
        addr	= prop["住所"] || prop["address"] || "unknown"
        desc	= prop["概要"] || prop["description"]
        objtype	= geom["type"] || "Point"
        jsonval	= geom["coordinates"]
        # Extract the first coords from jsonval
        coords = jsonval
        while coords[0].is_a?(Array)
          coords = coords[0]
        end
        lon,lat	= *coords
        if !lon.is_a?(Numeric) || !lat.is_a?(Numeric) then
          abort "Geom values are not real number(#{lon}, #{lat}) at #{name}."
        end
        # mapitem(ename, name, addr, lat, lon);
        # maptype(ename, maptype);
        # attribute(ename, attr, value);
        # object(ename, objtype, jsonval);
        db.execute("REPLACE INTO mapitem VALUES(?, ?, ?, ?, ?)",
                   ename, name, addr, lat, lon)
        db.execute("REPLACE INTO maptype VALUES(?, ?)", ename, maptype)
        db.execute("REPLACE INTO attribute VALUES(?, ?, ?)",
                   ename, "description", desc)
        db.execute("REPLACE INTO object VALUES(?, ?, ?)",
                   ename, objtype, JSON.generate(jsonval))
      end
    end
  end
end
