-- LUALOCALS < ---------------------------------------------------------
local klots, math, minetest
    = klots, math, minetest
local math_abs, math_deg
    = math.abs, math.deg
-- LUALOCALS > ---------------------------------------------------------

local modname = minetest.get_current_modname()

minetest.register_on_joinplayer(function(player)
		player:set_nametag_attributes({
				text = " ",
				color = {a = 0, r = 0, g = 0, b = 0}
			})
		player:set_properties({
				visual = "mesh",
				visual_size = {x = 0.9, y = 0.9, z = 0.9},
				mesh = modname .. "_model.b3d",
				textures = {modname .. "_skin.png"}
			})
	end)

local anims = {
	stand = {x = 0, y = 0},
	walk = {x = 3, y = 27},
	walk_mine = {x = 28, y = 52},
	mine = {x = 53, y = 77},
}

local pitch_mult = 2/3
local pitch_max = 60
local pitch_min = -15
local pitch_precision = 1

local player_hand_time = {}

function klots.player_hand_movement(player)
	local pname = player and player.get_player_name and player:get_player_name()
	if pname then player_hand_time[pname] = 0.3 end
end

klots.register_playerstep(function(player, data, dtime)
		local pitch = -math_deg(player:get_look_vertical()) * pitch_mult
		if pitch < pitch_min then pitch = pitch_min end
		if pitch > pitch_max then pitch = pitch_max end
		if not (data.headpitch and math_abs(data.headpitch - pitch)
			< pitch_precision) then
			data.headpitch = pitch
			player:set_bone_position("Head",
				{x = 0, y = 1/2, z = -pitch / 45},
				{x = pitch, y = 0, z = 0}
			)
		end

		local pname = player:get_player_name()
		local digging = player_hand_time[pname]
		player_hand_time[pname] = digging and (digging > dtime) and (digging - dtime) or nil

		local function setanim(anim, speedmod)
			anim.speed = 30 * (speedmod or 1)
			if data.anim and data.anim.x == anim.x
			and data.anim.y == anim.y
			and data.anim.speed == anim.speed then return end
			player:set_animation(anim, anim.speed, 0.1)
		end
		local control = player:get_player_control()
		local walking = control.up or control.down or control.left or control.right
		local flying = klots.player_control_get(player).param
		if flying then
			if digging then
				return setanim(anims.mine)
			elseif walking then
				return setanim(anims.walk, 0.2)
			else
				local pos = player:get_pos()
				pos.y = pos.y - 0.25
				local node = minetest.get_node(pos)
				local def = minetest.registered_nodes[node.name]
				if def and not def.walkable then
					return setanim(anims.walk, 0.2)
				end
			end
		elseif walking then
			if digging then
				return setanim(anims.walk_mine)
			else
				return setanim(anims.walk)
			end
		elseif digging then
			return setanim(anims.mine)
		end
		return setanim(anims.stand)
	end)
