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_node("pyutest_spawnpoints:spawnpoint", "Spawnpoint", {
  choppy = PyuTest.BLOCK_FAST
}, { "pyutest-spawnpoint.png" }, {
  on_rightclick = function(pos, node, clicker)
    if clicker == nil then return end
    if not clicker:is_player() then return end

    local name = clicker:get_player_name()
    spawnpoints[name] = pos
  end
})

core.register_craft({
  output = "pyutest_spawnpoints:spawnpoint",
  recipe = {
    { "pyutest_blocks:stone_block", "pyutest_blocks:stone_block", "pyutest_blocks:stone_block" },
    { "pyutest_blocks:stone_block", "pyutest_blocks:stone_block", "pyutest_blocks:stone_block" },
    { "pyutest_blocks:stone_block", "pyutest_blocks:stone_block", "pyutest_blocks:stone_block" },
  }
})
