-- LUALOCALS < ---------------------------------------------------------
local klots, minetest, string, table
    = klots, minetest, string, table
local string_rep, table_concat
    = string.rep, table.concat
-- LUALOCALS > ---------------------------------------------------------

local modname = minetest.get_current_modname()

if klots.editmode then return end

local crosshair_opacity = 64
local function handle_crosshair(player, data, show)
	if show and not data.crosshair then
		data.crosshair = player:hud_add({
				hud_elem_type = "image",
				position = {x = 0.5, y = 0.5},
				text = modname .. "_crosshair.png^[opacity:"
				.. crosshair_opacity,
				direction = 0,
				scale = {x = 1, y = 1},
				offset = {x = 0, y = 0},
				z_index = -100
			})
		player:get_inventory():set_stack("hand", 1,
			modname .. ":wieldhand")
	elseif data.crosshair and not show then
		player:hud_remove(data.crosshair)
		player:get_inventory():set_stack("hand", 1, "")
		data.crosshair = nil
	end
end

local credit_text = {
	"The End",
	". . . for now . . .",
	"",
	"",
	string_rep(". ", 24) .. ".",
	"",
	"HELP WANTED!",
	"Contributions welcome, especially:",
	"",
	"- level and puzzle design -",
	"- level decorating and environmental storytelling -",
	"- worldbuilding and story development -",
	"- textures and sound improvements -",
	"- novel and theme-fitting puzzle mechanics -",
	"",
	string_rep(". ", 24) .. ".",
	"",
	"",
	"https://gitlab.com/sztest/klots"
}
local function handle_credits(player, data, show)
	if show and not data.credits then
		data.credits = {}
		for i = 1, #credit_text do
			local lines = {}
			for j = 1, #credit_text do
				lines[#lines + 1] = i == j and credit_text[j] or ""
			end
			data.credits[i] = player:hud_add({
					hud_elem_type = "text",
					position = {x = 0.5, y = 0.5},
					text = table_concat(lines, "\n"),
					number = 0xffffff,
					z_index = -100
				})
		end
	elseif data.credits and not show then
		for i = 1, #data.credits do
			player:hud_remove(data.credits[i])
		end
		data.credits = nil
	end
end

klots.register_playerstep(function(player, data)
		local won = player:get_pos().y >= 10000
		local interact = minetest.check_player_privs(player, "interact")
		handle_crosshair(player, data, interact and not won)
		handle_credits(player, data, won)
	end)

minetest.register_on_joinplayer(function(player)
		player:hud_set_flags({crosshair = false})
	end)
