-- Määrame skeemi keskkonnamuutujast või vaikimisi 'public'
local schema = os.getenv("PGSCHEMA") or "public"
local tables = {}
-- Define the "countries" locator and get all country geometries from the
-- database. Use the import-countries.lua file to import them first, before
-- you run this.
local countries = osm2pgsql.define_locator({name = "countries"})
countries:add_from_db("SELECT code, ST_Subdivide(geom, 200) FROM " .. schema .. ".countries")

-- Funktsioon, mis eemaldab soovimatud võtmed tagidest
local function clean_tags(tags)
    local keys_to_remove = {
        "border_zone"
    }
    for _, key in ipairs(keys_to_remove) do
        tags[key] = nil
    end
    return next(tags) == nil
end

-- Defineerime relatsioonide tabeli, kuhu salvestame halduspiirid
tables.boundaries =
    osm2pgsql.define_relation_table(
    "ardok_administrative",
    {
        {column = "country", type = "text"},
        {column = "type", type = "text"},
        {column = "admin_level", type = "int"},
        {column = "name", type = "text"},
        {column = "code", type = "text"},
        {column = "countycode", type = "text"},
        {column = "parishcode", type = "text"},
        {column = "tags", type = "jsonb"},
        {column = "geom", type = "geometry", not_null = true} -- lubame erinevad geomeetriatüübid
    },
    {
        schema = schema,
        proj = 3301
    }
)

-- Peamine funktsioon, mis töötleb OSM relatsioone
function osm2pgsql.process_relation(object)
    local relation_type = object.tags["type"]

    local geom = object:as_multipolygon()
    if not geom then
        return
    end

    -- Kontrollime, kas geomeetria asub Eestis
    local cc = countries:first_intersecting(geom)
    if cc ~= "EE" then
        return
    end

    -- Töötleme ainult boundary-relatsioone
    if relation_type == "boundary" then
        local name = object.tags["name"]
        local type = object.tags["boundary"]
        local admin_level = object.tags.admin_level
		local code = object.tags["EHAK:code"]
		local countycode = object.tags["EHAK:countycode"]
		local parishcode = object.tags["EHAK:parishcode"]
        -- Eemaldame soovimatud tagid
        if clean_tags(object.tags) then
            return
        end

        -- Koostame rea andmebaasi jaoks
        local row = {
            country = cc,
            type = type,
            admin_level = admin_level,
            name = name,
			code = code,
			countycode = countycode,
			parishcode = parishcode,
            tags = object.tags,
            geom = geom
        }

        tables.boundaries:insert(row)
    end
end
