-- LUALOCALS < ---------------------------------------------------------
local get_mod_api, minetest, piredo_player
    = get_mod_api, minetest, piredo_player
-- LUALOCALS > ---------------------------------------------------------

local api = get_mod_api()
local modname = minetest.get_current_modname()

piredo_player.register_player_init(function()
		api.screenfade()
		return api.save_player_pos()
	end)

minetest.register_tool(":", {
		wield_image = "wieldhand.png",
		on_use = function(_, user, pointed)
			-- Disable digging animation, one punch per click
			api.player_hand_movement(user)
			if not (user and pointed and pointed.under) then return end
			local node = minetest.get_node(pointed.under)
			local def = minetest.registered_nodes[node.name]
			if def and def.on_punch then
				def.on_punch(pointed.under, node, user, pointed)
			end
		end,
		on_place = function(stack, user, pointed)
			api.player_hand_movement(user)
			return minetest.item_place(stack, user, pointed)
		end
	})

minetest.register_node(modname .. ":wieldhand", {
		description = "",
		drawtype = "mesh",
		mesh = modname .. "_hand.obj",
		tiles = {modname .. "_skin.png"},
		use_texture_alpha = "clip",
		wield_scale = {x = 2, y = 2, z = 2},
		groups = {not_in_creative_inventory = 1},
		stack_max = 1,
		node_placement_prediction = "",
		paramtype = "light",
		on_punch = minetest.remove_node
	})

local function common(player)
	player:get_inventory():set_size("hand", 1)
	player:get_inventory():set_size("main", 20)
	player:hud_set_hotbar_selected_image(modname .. "_hotbar_active.png")
	player:set_inventory_formspec("")
	player:set_formspec_prepend("formspec_version[6]bgcolor[#000000E0;true;#000000E0]")
	player:set_armor_groups({
			immortal = 1,
			fall_damage_add_percent = -100
		})
	player:hud_set_flags({
			minimap = false,
			basic_debug = false,
			healthbar = false,
			breathbar = false,
			minimap_radar = false,
		})
	player:set_properties({zoom_fov = 45})
end
local function newplayer(player)
	common(player)
	player:set_physics_override({speed = 1.6, gravity = 1})
	player:hud_set_flags({
			crosshair = true,
			wielditem = true,
		})
	player:get_inventory():set_stack("hand", 1, modname .. ":wieldhand")
end
local function oldplayer(player)
	common(player)
	player:set_physics_override({speed = 0, gravity = 0})
	player:hud_set_flags({
			crosshair = false,
			wielditem = false,
		})
	player:get_inventory():set_stack("hand", 1, "")
end

minetest.register_on_joinplayer(function(player)
		return (player == api.mainplayer() and newplayer or oldplayer)(player)
	end)
api.register_on_playerswap(function(newp, oldp)
		if oldp then oldplayer(oldp) end
		if newp then newplayer(newp) end
	end)
