local master = dwarf_characters
local intramodcom = dwarf_characters.intramodcom
local S = minetest.get_translator("dwarf_characters")

--persistent storage
local known_player_appearances =
	intramodcom.register_for_storage("known_player_appearances",
	{})



--non-persistent storage
local player_textures = {}









local function get_random_appearance()
	local appearance = {}
	appearance.skin_color = math.random(1, 10) / 10
	appearance.hair_brightness = math.random(1, 10) / 10
	appearance.hair_redness = math.random(1, 10) / 10

	local model_list = dwarf_characters.get_models()
	local model = model_list[math.random(#model_list)]
	appearance.model = model.name
	appearance.sex = model.sex


	appearance.beard = dwarf_characters.get_random_beard(appearance.sex)


	appearance.hair = dwarf_characters.get_random_hair()


	appearance.armor = dwarf_characters.get_random_armor()


	appearance.helmet = dwarf_characters.get_random_helmet()
	return appearance
end



local function get_appearance(name)
	local appearance = known_player_appearances[name]
	if not appearance
	then
		appearance = get_random_appearance()
	end
	return appearance
end


local get_textures = intramodcom.get_textures
local animations = intramodcom.animations


minetest.register_chatcommand("newappearance",
{
	privs = {interact = true},
	func = function(name)
		local player = minetest.get_player_by_name(name)
		if player
		then
			local appearance = get_random_appearance()
			known_player_appearances[name] = appearance
			local props = player:get_properties()
			props.textures = get_textures(appearance)
			props.mesh = appearance.model
			player:set_properties(props)
			return true, S("Your appearance changed! (unless you got the same as before by random chance)")
		else
			return true, S("You must be online for this command to work.")
		end
	end
})





-- Update appearance when the player joins
minetest.register_on_joinplayer(function(player)
	local name = player:get_player_name()


	do --object property stuff
		local properties = player:get_properties()

		local appearance = get_appearance(name)
		properties.mesh = appearance.model
		properties.textures = get_textures(appearance)

		properties.visual = "mesh"
		properties.eye_height = 1.3
		properties.visual_size = {x = 1, y = 1, z = 1}
		player:set_properties(properties)
	end
	player:set_local_animation(
		animations.stand(),
		animations.walk(),
		animations.mine(),
		animations.walk_mine(),
		45)
	player:set_animation(animations.stand(), 45, 0, true)
end)
minetest.register_on_dieplayer(function(player)
	player:set_animation(animations.die(), 45, 0, false)
end)
minetest.register_on_respawnplayer(function(player)

	player:set_animation(animations.stand(), 45, 0, true)
end)
