local player_data = {}

--[[ Player Setup ]] --
minetest.register_on_joinplayer(function(player)
	-- Initialize Data --
	local name = player:get_player_name()
	player_data[name] = {}

	-- Inventory --
	local inv_size = 2
	local inv = player:get_inventory()
	inv:set_size("main", inv_size)
	player:set_inventory_formspec("")
	player:hud_set_hotbar_itemcount(inv_size)
	inv:set_stack("main", 1, ItemStack("ikea_tools:flashlight_off"))

	-- Physics --
	player:set_physics_override({speed = 1, jump = 0, sneak = false, sneak_glitch = false, new_move = true})
	player:set_properties({stepheight = 0})

	-- Skybox --
	player:set_sky({
		type = "regular",
		sky_color = {day_horizon = "#414141", dawn_horizon = "#303030", night_horizon = "#303030", indoors = "#303030"},
	})

	-- Status Vignette --
	player:hud_set_flags({healthbar = false})
	player_data[name].vign_id = player:hud_add({
		name = "Player Status Vignette",
		hud_elem_type = "image",
		alignment = {x = 1, y = 1},
		scale = {x = -100, y = -100},
		text = "ikea_player_vignette.png^[opacity:0",
		z_index = -400,
	})
end)

--[[ Player Updates ]] --
local timer = 0
local hp_timer = 0

minetest.register_globalstep(function(dtime)
	timer = timer + dtime
	if timer < 0.10 then
		return
	end

	timer = 0
	hp_timer = hp_timer + dtime

	for _, player in ipairs(minetest.get_connected_players()) do
		if player then
			local name = player:get_player_name()
			local data = player_data[name]
			local props = player:get_properties()
			local hp = player:get_hp()

			-- Healing Over Time --
			if (hp_timer > 1) and (hp < props.hp_max) then
				hp = hp + 1
				hp_timer = 0
			end

			-- Satus Vignette --
			if (not data.hp_last) or (hp ~= data.hp_last) then
				vign_texture = "(ikea_player_vignette.png^[multiply:#5c3d41)^[opacity:" .. tostring((1 - (hp / props.hp_max)) * 255)

				if not data.vign_id then
					error("Player Vignette ID Not Set!")
				end
				player:hud_change(data.vign_id, "text", vign_texture)

				data.hp_last = hp
			end

			player:set_hp(hp)
		end
	end
end)

minetest.register_on_leaveplayer(function(player)
	local name = player:get_player_name()
	player_data[name] = nil
end)

--[[ Hand ]] --
local STATIC_GROUPCAP --
if DEBUG then
	STATIC_GROUPCAP = {times = {[1] = 1.00}, uses = 0}
end

minetest.register_item(":", {
	type = "none",
	wield_image = "wieldhand.png",
	wield_scale = {x = 1, y = 1, z = 3},
	tool_capabilities = {
		full_punch_interval = 0.5,
		max_drop_level = 0,
		groupcaps = {
			static = STATIC_GROUPCAP,

			oddly_breakable_by_hand = {times = {[1] = 1.00}, uses = 0},

			carryable = {times = {[1] = 1.00}, uses = 0},
		},
		damage_groups = {fleshy = 2},
	},
})

--[[ General Behavior ]]--
-- Disable Item Dropping --
function minetest.item_drop(itemstack, user, pointed_thing)
    return -- Nothing!
end
