-- LUALOCALS < ---------------------------------------------------------
local ipairs, klots, minetest, pairs, type, vector
    = ipairs, klots, minetest, pairs, type, vector
-- LUALOCALS > ---------------------------------------------------------

local modname = minetest.get_current_modname()

local colors = {
	{desc = "Red", hex = "ff0000"},
	{desc = "Green", hex = "00ff00"},
	{desc = "Blue", hex = "0000ff"},
	{desc = "Cyan", hex = "00ffff"},
	{desc = "Yellow", hex = "ffff00"},
	{desc = "Magenta", hex = "ff00ff"}
}
for i, v in ipairs(colors) do
	v.id = i
	v.name = v.desc:lower()
end

local regall
do
	local function colorize(thing, color)
		if type(thing) == "string" then
			return thing .. "^[multiply:#" .. color
		end
		if type(thing) ~= "table" then return thing end
		local tbl = {}
		if thing.name then
			for k, v in pairs(thing) do tbl[k] = v end
			tbl.name = colorize(tbl.name, color)
		else
			for k, v in pairs(thing) do tbl[k] = colorize(v, color) end
		end
		return tbl
	end

	local function deepcopy(t)
		if type(t) ~= "table" then return t end
		local u = {}
		for k, v in pairs(t) do u[k] = deepcopy(v) end
		return u
	end

	regall = function(basename, basedef)
		for _, color in ipairs(colors) do
			local def = deepcopy(basedef)
			if def.description then def.description = def.description .. " - " .. color.desc end

			for k in pairs({tiles = 1, inventory_image = 1, wield_image = 1, special_tiles = 1}) do
				def[k] = colorize(def[k], color.hex)
			end

			def.groups = def.groups or {}
			def.groups.klots_color = color.id
			def.groups.klot = 1

			def.sounds = def.sounds or {
				dug = {
					name = "klots_pieces_slider_move",
					gain = 0.7
				},
				footstep = {
					name = "klots_pieces_slider_touch",
					gain = 0.45
				},
				place = {
					name = "klots_pieces_slider_move",
					gain = 1
				},
				hitplayer = {
					name = "klots_pieces_slider_hitplayer",
					gain = 1
				}
			}

			minetest.register_node(basename .. "_" .. color.name, def)
		end
	end
end

regall(modname .. ":klot", {
		description = "Sliding Block",
		drawtype = klots.editmode and "normal" or "airlike",
		tiles = {modname .. "_base.png"},
		paramtype = "light",
		on_actuate = function(pos, _, pointed)
			local commit, fail = klots.klot_try_move(pos,
				vector.subtract(pointed.under, pointed.above))
			return commit and commit() or fail and fail()
		end
	})
regall(modname .. ":klot_pull", {
		description = "Sliding Block",
		drawtype = klots.editmode and "normal" or "airlike",
		tiles = {modname .. "_base.png^" .. modname .. "_pull.png"},
		paramtype = "light",
		on_actuate = function(pos, _, pointed)
			local commit, fail = klots.klot_try_move(pos,
				vector.subtract(pointed.above, pointed.under))
			return commit and commit() or fail and fail()
		end
	})
