local S = minetest.get_translator("in_game_guide")

in_game_guide = {}


local pages = {}
local root_page
local root_page_back_button

function in_game_guide.set_root_page_back_button_name(name)
	assert(type(name) == "nil" or type(name) == "string",
		"Cannot set non-string or nil value as back_button name.")
	root_page_back_button = name
end

--generates a formspec from a page definition
local function to_formspec(page_definition)
	--for background of title TODO: fix this
	local title_border_offset = string.len(page_definition.title)
	title_border_offset = title_border_offset / 8.5 + 0.5

	local spec =
	{
		"size[12,8]" ..
		"real_coordinates[true]" ..
		"background[3,0.6;8,0.7;in_game_guide_background.png]" ..
		"label[3.05,1;" .. page_definition.title .."]" ..
		"background[3,2;8,5;in_game_guide_background.png]" ..
		"textarea[3,2;8,5;;;" .. page_definition.text .. "]"
	}
	--back button
	if (page_definition.parent and page_definition ~= root_page) or
		(root_page_back_button and page_definition == root_page)
	then
		local back_button = "back"
		if page_definition == root_page
		then
			back_button = root_page_back_button
		end
		table.insert(spec, "button[0.5,1;1,1;" .. back_button .. ";<]")
	end
	--list of child pages
	if page_definition.children
	then
		table.insert(spec, "table[0.5,2;2.5,5;page_children;")
		local children = {}
		for _, child in ipairs(page_definition.children)
		do
			child = pages[child]
			table.insert(children, child.title);
			table.insert(children, ",")
		end
		children[#children] = nil --remove last comma
		table.insert(spec, table.concat(children))


		table.insert(spec, ";1]")
	end

	return page_definition.name, table.concat(spec)
end

function in_game_guide.set_root_page(name)
	assert(pages[name], "There is no page registered with name " .. name)
	root_page = pages[name]
end

function in_game_guide.show_root_page(playername, return_button_name)
	assert(root_page, "There is no root page set")
	minetest.show_formspec(playername, to_formspec(root_page, return_button_name))
end

minetest.register_on_player_receive_fields(function(player, formname, fields)
		local page = pages[formname]
		if not page
		then
			return false
		end
		if fields.back
		then
			local parent = page.parent
			if parent
			then
				minetest.show_formspec(
					player:get_player_name(),
					to_formspec(pages[parent]))
				return true
			end
		end
		local page_children = fields.page_children
		if page_children
		then
			local evt = minetest.explode_table_event(page_children)
			if evt.type ~= "DCL" --if not double click
			then
				return true
			end
			minetest.show_formspec(
				player:get_player_name(),
				to_formspec(pages[page.children[evt.row]]))
		end
		return true
	end)
local err = "Error registering guide page: "
function in_game_guide.register_page(name, definition)
	local split_name = string.split(name, ":")
	assert(not pages[name],
		err .. "There is already a page registered with name " .. name)

	assert(minetest.get_current_modname() == split_name[1],
		err .. "Name must be of format 'modname:pagename'")
	assert(type(definition.text) == "string",
		err .. "field 'text' of definition must be a string")
	definition.text = minetest.formspec_escape(definition.text)

	assert(type(definition.title) == "string",
		err .. "field 'title' of definition must be a string")
	definition.title = minetest.formspec_escape(definition.title)

	if type(definition.children) == "table"
	then
		assert(#definition.children > 0,
			err .. "field 'children' must not be an empty table, set it to nil instead.")
		for _, childname in ipairs(definition.children)
		do
			assert(type(childname) == "string",
				err .. "Cannot try to register non-string value as child name")
			assert(pages[childname],
				err .. "There is no registered page with name " ..
					childname .. " to be set as child.")
			assert(not pages[childname].parent,
				err .. "Child " .. childname .. " already has a parent.")
			pages[childname].parent = name
		end
	else
		assert(type(definition.children) == "nil",
			"Error registering guide page: field 'children of definition must be a table or nil")
	end
	definition.name = name

	pages[name] = definition
end


minetest.register_chatcommand("guide",
	{
		description = S("Shows the guide screen"), --TODO: translate
		privs = {},
		func = function(name, param)
			local player = minetest.get_player_by_name(name)
			if player
			then
				if root_page
				then
					in_game_guide.show_root_page(name)
					return true
				end
			end
			return false, S("There is no guide page set as root")
		end,
	})


--testing stuff
--[[
in_game_guide.register_page("in_game_guide:testchild",
	{
		text = "henlo im a child",
		title = "Test child",
	})

in_game_guide.register_page("in_game_guide:test",
	{
		text =
			"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Dolor sed viverra ipsum nunc aliquet bibendum enim. In massa tempor nec feugiat. Nunc aliquet bibendum enim facilisis gravida. Nisl nunc mi ipsum faucibus vitae aliquet nec ullamcorper. Amet luctus venenatis lectus magna fringilla. Volutpat maecenas volutpat blandit aliquam etiam erat velit scelerisque in. Egestas egestas fringilla phasellus faucibus scelerisque eleifend. Sagittis orci a scelerisque purus semper eget duis. Nulla pharetra diam sit amet nisl suscipit. Sed adipiscing diam donec adipiscing tristique risus nec feugiat in. Fusce ut placerat orci nulla. Pharetra vel turpis nunc eget lorem dolor. Tristique senectus et netus et malesuada." ..
			"Etiam tempor orci eu lobortis elementum nibh tellus molestie. Neque egestas congue quisque egestas. Egestas integer eget aliquet nibh praesent tristique. Vulputate mi sit amet mauris. Sodales neque sodales ut etiam sit. Dignissim suspendisse in est ante in. Volutpat commodo sed egestas egestas. Felis donec et odio pellentesque diam. Pharetra vel turpis nunc eget lorem dolor sed viverra. Porta nibh venenatis cras sed felis eget. Aliquam ultrices sagittis orci a. Dignissim diam quis enim lobortis. Aliquet porttitor lacus luctus accumsan. Dignissim convallis aenean et tortor at risus viverra adipiscing at.",
		title = "Lorem Ipsum",
		children = {"in_game_guide:testchild"},
	})



in_game_guide.set_root_page("in_game_guide:test")
--]]
