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

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

core.register_chatcommand("sethome", {
	params = "<name>",
	description = "Sets the position of home <NAME>",
	func = function(name, param)
		local player = core.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
})

core.register_chatcommand("tphome", {
	params = "<name>",
	description = "Teleports to home <NAME>",
	func = function(name, param)
		local player = core.get_player_by_name(name)
		local home = homes[name][param]

		if home ~= nil then
			player:set_pos(home)
			return true, "Teleported to home: " .. param
		else
			return false, "No such home exists!"
		end
	end
})

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

core.register_chatcommand("deletehome", {
	description = "Delete a home",
	func = function(name, param)
		homes[name][param] = nil
		return true, string.format("Home `%s` has been deleted", param)
	end
})

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

core.register_on_shutdown(save_data)

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

	core.after(10, interval)
end

interval()
