local storage = core.get_mod_storage()
local spawnpoints = core.deserialize(storage:get("player_spawns")) or {}

core.register_on_joinplayer(function(player)
	local name = player:get_player_name()
	if spawnpoints[name] == nil then
		spawnpoints[name] = player:get_pos()
	end
end)

core.register_on_respawnplayer(function(player)
	local name = player:get_player_name()
	if spawnpoints[name] ~= nil then
		player:set_pos(spawnpoints[name])
		return true
	end
end)

local function save_data()
	storage:set_string("player_spawns", core.serialize(spawnpoints))
end

core.register_on_shutdown(save_data)
PyuTest.register_interval(save_data, 10)

PyuTest.make_item("pyutest_spawnpoints:spawnpoint", "Spawnpoint Setter", {}, "pyutest-star.png", {
	color = PyuTest.COLORS.khaki[2],
	on_use = function(itemstack, clicker)
		if clicker == nil then return end
		if not clicker:is_player() then return end

		local name = clicker:get_player_name()
		spawnpoints[name] = clicker:get_pos()

		itemstack:take_item()
		return itemstack
	end
})

core.register_craft({
	output = "pyutest_spawnpoints:spawnpoint",
	recipe = {
		{ "group:cobble", "group:cobble", "group:cobble" },
		{ "group:cobble", "group:cobble", "group:cobble" },
		{ "group:cobble", "group:cobble", "group:cobble" },
	}
})
