local storage = minetest.get_mod_storage()
local homes = minetest.deserialize(storage:get("player_homes")) or {}

minetest.register_on_joinplayer(function (player)
  local name = player:get_player_name()
  if homes[name] == nil then
    homes[name] = {}
  end
end)

minetest.register_chatcommand("sethome", {
  params = "<name>",
  description = "Sets the position of home <NAME>",
  func = function (name, param)
    local player = minetest.get_player_by_name(name)
    local pos = player:get_pos()
    homes[name][param] = pos
    return true, string.format("Set home `%s` position to (%d, %d, %d)", param, pos.x, pos.y, pos.z)
  end
})

minetest.register_chatcommand("tphome", {
  params = "<name>",
  description = "Teleports to home <NAME>",
  func = function (name, param)
    local player = minetest.get_player_by_name(name)
    player:set_pos(homes[name][param] or player:get_pos())
  end
})

minetest.register_chatcommand("listhomes", {
  description = "Lists all your homes",
  func = function (name)
    for k, v in pairs(homes[name]) do
      minetest.chat_send_player(name, string.format("%s - (%d, %d, %d)", k, v.x, v.y, v.z))
    end
    return true, "Listed all homes"
  end
})

local function save_data()
  storage:set_string("player_homes", minetest.serialize(homes))
end

minetest.register_on_shutdown(save_data)

local first_run = true
local function interval()
  if first_run then
    first_run = false
  else
    save_data()
  end

  minetest.after(10, interval)
end

interval()
