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

crafting.register_type("toil")

--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("Toiling 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[2] =
		crafting.make_result_selector(player, "toil", 1, {x = 8, y = 3}, context)
	local formspec = table.concat(base_formspec)
	minetest.show_formspec(player:get_player_name(), "toiling_table", formspec)
end

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

minetest.register_node(modname .. ":toiling_table",
	{
		description = S("Toiling Table"),
		drawtype = "mesh",
		mesh = modname .. "_toiling_table.obj",
		tiles = {"eg_trees_wood_sides.png", "eg_trees_wood_slice.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",
		}
	})

minetest.register_craft(
	{
		type = "shapeless",
		output = modname .. ":toiling_table",
		recipe = {"eg_trees:wood"},
	})
crafting.register_recipe(
	{
		type = "toil",
		output = "eg_storage_barrels:barrel",
		items = {"eg_trees:wood 4"},
		always_known = true,
	})
crafting.register_recipe(
	{
		type = "toil",
		output = "eg_woodstuffs:planks 4",
		items = {"eg_trees:wood"},
		always_known = true,
	})
