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

crafting.register_type("gardening")

--context tables are used for remembering which page a player is on
local contexts = {}
minetest.register_on_joinplayer(function(player)
		contexts[player:get_player_name()] = {}
	end)
minetest.register_on_leaveplayer(function(player)
		contexts[player:get_player_name()] = nil
	end)

local base_formspec =
{
	"formspec_version[1]",
	"size[8.1,9]",
	"label[0.1,0.1;",
	S("Gardening Table"),
	"]",
	"list[current_player;main;0,5.3;8,4]",
	"container[0, 0.7]",
}
base_formspec =
{
	table.concat(base_formspec),
	nil,
	"container_end[]",
}
local result_selector_pos = #base_formspec - 1
local function show_formspec(player, context)
	context = contexts[player:get_player_name()]
	base_formspec[result_selector_pos] =
		crafting.make_result_selector(player, "gardening", 1, {x = 8, y = 3}, context)
	local formspec = table.concat(base_formspec)
	minetest.show_formspec(player:get_player_name(), "gardener_table", formspec)
end

minetest.register_on_player_receive_fields(function(player, formname, fields)
		if formname ~= "gardener_table"
		then
			return
		end
		local context = contexts[player:get_player_name()]
		if crafting.result_select_on_receive_results(player, "gardening", 1, context, fields)
		then
			show_formspec(player, context)
		end
		return true
	end)

minetest.register_node(modname .. ":gardener_table",
	{
		description = S("Gardening Table"),
		drawtype = "mesh",
		mesh = modname .. "_gardener_table.obj",
		tiles = {"eg_trees_wood_sides.png", "eg_trees_wood_slice.png", "eg_trees_leaves.png"},
		groups = {deconstructable = 3},
		is_ground_content = false,
		on_rightclick = function(pos, node, clicker)
			show_formspec(clicker)
		end,
		sounds =
		{
			dig = "wood_high_dig",
			dug = "wood_low_dug",
			place = "wood_low_place",
			footstep = "wood_low_footstep",
		}
	})

crafting.register_recipe(
	{
		type = "toil",
		output = modname .. ":gardener_table",
		items = {"eg_trees:wood 2", "eg_trees:leaves"},
		level = 1,
		always_known = true,
	})

crafting.register_recipe(
	{
		type = "gardening",
		output = "eg_trees:sapling",
		items = {"eg_trees:leaves 4"},
		level = 1,
		always_known = true,
	})

crafting.register_recipe(
	{
		type = "gardening",
		output = "eg_mapgen:grass",
		items = {"eg_trees:leaves 4"},
		level = 1,
		always_known = true,
	})

crafting.register_recipe(
	{
		type = "gardening",
		output = "eg_apples:plant",
		items = {"eg_trees:leaves 4", "eg_apples:appleapple"},
		level = 1,
		always_known = true,
	})
