minetest.register_abm({
	label = "Seed to plant",
	nodenames = { "farming:wheat_seeds", "farming:carrot" },
	interval = 4,
	chance = 10,
	catch_up = false,
	action = function(pos, node)
		local n_plant = { name = farming.seed_plant[node.name] }
		minetest.set_node(pos, n_plant)
	end,
})

minetest.register_abm({
	label = "Soil to Dirt conversion",
	nodenames = { "farming:soil" },
	interval = 1,
	chance = 1,
	catch_up = false,
	action = function(pos)
		local above_pos = { x = pos.x, y = pos.y + 1, z = pos.z }
		local above_node = minetest.get_node(above_pos)
		if above_node.name ~= "air" and not farming.is_crop(above_node.name) then
			minetest.set_node(pos, { name = "default:dirt" })
		end
	end,
})

minetest.register_abm({
	label = "Seed / plant drop",
	nodenames = { "farming:wheat_seeds", "farming:wheat", "farming:carrot", "farming:carrot_grown" },
	interval = 1,
	chance = 1,
	catch_up = false,
	action = function(pos, node)
		pos.y = pos.y - 1
		local below = minetest.get_node(pos)
		if below.name ~= "farming:soil" then
			local n_air = { name = "air" }
			pos.y = pos.y + 1
			minetest.set_node(pos, n_air)
			minetest.add_item(pos, node)
		end
	end,
})

minetest.register_abm({
	label = "Cane cactus drop",
	nodenames = { "farming:sugar_cane", "farming:cactus" },
	interval = 1,
	chance = 1,
	catch_up = false,
	action = function(pos, node)
		pos.y = pos.y - 1

		local above = minetest.get_node(pos)
		if above.name == "air" then
			local n_air = { name = "air" }
			pos.y = pos.y + 1
			minetest.set_node(pos, n_air)
			minetest.add_item(pos, node)
		end
	end,
})

minetest.register_abm({
	label = "Cane no water",
	nodenames = { "farming:sugar_cane" },
	interval = 1,
	chance = 1,
	catch_up = false,
	action = function(pos, node)
		pos.y = pos.y - 1
		if minetest.get_node(pos).name == "farming:sugar_cane" then
			return
		end
		for _, i in ipairs({
			{ x = 1, y = 0, z = 0 },
			{ x = 0, y = 0, z = 1 },
			{ x = -1, y = 0, z = 0 },
			{
				x = 0,
				y = 0,
				z = -1,
			},
		}) do
			if minetest.get_node(vector.add(pos, i)).name == "default:water_flowing" then
				return
			end
			if minetest.get_node(vector.add(pos, i)).name == "default:water_source" then
				return
			end
		end
		pos.y = pos.y + 1
		local n_air = { name = "air" }
		minetest.set_node(pos, n_air)
		minetest.add_item(pos, node)
	end,
})

minetest.register_abm({
	label = "Cane cactus grow",
	nodenames = { "farming:sugar_cane", "farming:cactus" },
	interval = 1,
	chance = 10,
	catch_up = false,
	action = function(pos, node)
		pos.y = pos.y + 1

		local above = minetest.get_node(pos)
		if above.name == "air" then
			pos.y = pos.y - 3
			if minetest.get_node(pos).name == node.name then
				return
			end
			pos.y = pos.y + 3
			minetest.set_node(pos, node)
		end
	end,
})
