local tables = {}
local schema = os.getenv("PGSCHEMA") or "public"
local count = 0
local skipped = 0

tables.admin = osm2pgsql.define_way_table('administrative_polygon', {
  { column = 'name', type = 'text' },
  { column = 'admin_level', type = 'text' },
  { column = 'boundary', type = 'text' },
  { column = 'geom', type = 'geometry' }
}, {
  schema = schema,
  proj = 3301
})

local function try_insert(object)
  local boundary = object.tags.boundary
  local admin_level = object.tags.admin_level
  if boundary == 'administrative' and admin_level then
    local geom = object:as_polygon()
    if geom then
      tables.admin:insert({
        name = object.tags.name,
        admin_level = admin_level,
        boundary = boundary,
        geom = geom
      })
      count = count + 1
    else
      skipped = skipped + 1
    end
  end
end

function osm2pgsql.process_way(object)
  try_insert(object)
end

function osm2pgsql.process_relation(object)
  try_insert(object)
end

function osm2pgsql.process_area(object)
  try_insert(object)
end

function osm2pgsql.process_end()
  print("Imporditud halduspiirkondi: " .. count)
  print("Vahele jäetud (puuduv geomeetria): " .. skipped)
end
