-- LUALOCALS < ---------------------------------------------------------
local core, math, nc
    = core, math, nc
local math_random
    = math.random
-- LUALOCALS > ---------------------------------------------------------

local modname = core.get_current_modname()

nc.register_craft({
		label = "melt sand to glass",
		action = "cook",
		touchgroups = {flame = 3},
		neargroups = {coolant = 0},
		duration = 20,
		cookfx = true,
		indexkeys = {"group:sand"},
		nodes = {
			{
				match = {groups = {sand = true}},
				replace = modname .. ":glass_hot_source"
			}
		},
		after = function(pos)
			nc.dnt_set(pos, "fluidwander_glass")
		end
	})

nc.register_cook_abm({
		nodenames = {"group:sand"},
		neighbors = {"group:flame"},
		neighbors_invert = true
	})

local src = modname .. ":glass_hot_source"
local flow = modname .. ":glass_hot_flowing"

local function near(pos, crit)
	return #nc.find_nodes_around(pos, crit, {1, 1, 1}, {1, 0, 1}) > 0
end

nc.register_craft({
		label = "cool clear glass",
		action = "cook",
		priority = -1,
		duration = 120,
		touchgroups = {flame = 0},
		neargroups = {coolant = 0},
		cookfx = {smoke = true, hiss = true},
		check = function(pos)
			return not near(pos, {flow})
		end,
		indexkeys = {src},
		nodes = {
			{
				match = src,
				replace = modname .. ":glass"
			}
		}
	})

nc.register_craft({
		label = "cool float glass",
		action = "cook",
		duration = 120,
		touchgroups = {flame = 0},
		neargroups = {coolant = 0},
		cookfx = {smoke = true, hiss = true},
		check = function(pos)
			return not near(pos, {flow})
		end,
		indexkeys = {src},
		nodes = {
			{
				match = src,
				replace = modname .. ":glass_float"
			},
			{
				y = -1,
				match = {groups = {lava = true}}
			}
		}
	})

nc.register_craft({
		label = "quench opaque glass",
		action = "cook",
		cookfx = true,
		touchgroups = {flame = 0},
		neargroups = {coolant = 1},
		check = function(pos)
			return (not near(pos, {flow}))
		end,
		indexkeys = {src},
		nodes = {
			{
				match = src,
				replace = modname .. ":glass_opaque"
			}
		}
	})
nc.register_craft({
		label = "quench crude glass",
		action = "cook",
		cookfx = true,
		touchgroups = {flame = 0},
		neargroups = {coolant = 1},
		check = function(pos)
			return near(pos, {flow})
		end,
		indexkeys = {src},
		nodes = {
			{
				match = src,
				replace = modname .. ":glass_crude"
			}
		}
	})

nc.register_cook_abm({nodenames = {src}})

nc.register_fluidwandering(
	"glass",
	{src},
	2,
	function(pos, _, gen)
		if gen < 16 or math_random(1, 2) == 1 then return end
		core.set_node(pos, {name = modname .. ":glass_crude"})
		nc.sound_play("nc_api_craft_hiss", {gain = 1, pos = pos})
		nc.smokeburst(pos)
		nc.dynamic_shade_add(pos, 1)
		nc.fallcheck(pos)
		return true
	end
)
