#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
Encoding.default_external = 'utf-8'
require 'json'
require 'nkf'

jbase = {"type" => "FeatureCollection"}
features = []
format = "kml"


if !ARGV[0] then
  print(<<-EOF)
	Usage: #{$0} umap.geojson
	Requires: ogr2ogr	Convert GeoJSON to KML
	EOF
  exit 2
end

while /^-(.*)/ =~ ARGV[0]
  case $1
  when "g"
    format = "geojson"
  end
  ARGV.shift
end

# 表示名,種別,正式名称,画像ファイル,住所,電話番号,説明文,筆者,撮影者

gj = JSON.load(open(ARGV[0]){|g|g.read})
if gj["type"] != "FeatureCollection"
  abort "Not a GeoJSON"
end
gj["features"].each{|f|
  prop = f["properties"]
  if prop && prop.length > 0
    # Copy "name" property to "表示名"
    prop["表示名"] = (prop["表示名"] || prop["name"])
    # Rename "description" property to "説明文"
    if prop["description"] then
      prop["説明文"] = prop["description"]
      prop.delete("description")
    end
    if prop["説明文"]
      files = prop["説明文"].scan(%r,{{(.*)/(.*\.jpg)}},i).collect{|n|
        n[1]
      }
      files[0] and prop["画像ファイル名"] = files.join(';')
      prop["説明文"].gsub!(/{{.*?}}\s*/, "") # Remove {{..}} from description
    end
    sorted = {"name"=>"", "表示名"=>"", "説明文"=>""}
    sorted.merge!(prop)
    f["properties"] = sorted
  end
}
outname = ARGV[0].sub(/\.*?/, "") + ".kml"

case format
when /kml/i
  open("| ogr2ogr -f KML /vsistdout/ /vsistdin/", "w+") do |o|
    Thread.new {
      # o.puts NKF.nkf("-w -Z0", JSON.pretty_generate(gj))
      o.puts NKF.nkf("-w -Z0", JSON.dump(gj))
      o.close_write
    }
    puts o.read
  end
when /geojson/i
  print NKF.nkf("-w -Z0", JSON.pretty_generate(gj))
end
