local mod_name = minetest.get_current_modname()
local S = minetest.get_translator(mod_name)

local has_tcraft = minetest.get_modpath("pmb_tcraft") ~= nil

local function desaturate(color, amount)
    local desatcolor = "#"
    local tot = 0
    local max = -1
    local rgb = {}
    for i=1, 3 do
        local seg = string.sub(color, (i*2), (i*2) + 1)
        local val = tonumber(seg, 16)
        rgb[i] = val
        if max < val then max = val end
        tot = tot + val
    end
    local avg = tot / 3

    for i = 1, 3 do
        rgb[i] = rgb[i] + (max - rgb[i]) * amount

        desatcolor = desatcolor..string.format("%X", rgb[i])
    end

    return desatcolor
end

for i, def in ipairs(pmb_dyes.dye_list) do
    local node_name = "pmb_terracotta:"..def.name

    local desatcolor = desaturate(def.color, 0.2)

    minetest.register_node(node_name, {
        description = S(def.color_name.." Terracotta"),
        _tt_long_desc = S("Fired, dyed clay"),
        groups = {
            full_solid = 1, terracotta = 1, oddly_breakable_by_hand = 3,
            solid = 1, suffocates = 2, cracky = 1 },
        tiles = { "pmb_terracotta_base.png"..
        "^[multiply:"..desatcolor.."^[colorize:"..desatcolor..":"..(def.colorize_amount or 0)/10 },
        sounds = pmb_sounds.default_stone(),
    }) pmb_util.register_all_shapes(node_name)

    if has_tcraft then
        pmb_tcraft.register_craft({
            output = node_name .. " 8",
            items = {
                [def.dye_item_name] = 1,
                ["pmb_items:clay_ball"] = 8
            }
        })
    end
end
