-- Handles giving players joining initial items and metadata values for Zoonami

-- Respawn settings
local settings = core.settings
local resupply_on_respawn = settings:get_bool("zoonami_resupply_on_respawn", true)

core.register_on_joinplayer(function(player)
	local inv = player:get_inventory()
	local meta = player:get_meta()
	local pos = player:get_pos()
	
	-- Settings that are only initialized one time for each player
	local initialized = core.deserialize(meta:get_string("zoonami_initialized"))
	initialized = type(initialized) == "table" and initialized or {}
	
	if not initialized.guide_book_item then
		core.add_item(pos, inv:add_item("main", "zoonami:guide_book"))
		initialized.guide_book_item = true
	end
	if not initialized.backpack_item then
		core.add_item(pos, inv:add_item("main", "zoonami:backpack"))
		initialized.backpack_item = true
	end
	if not initialized.automatic_zoom then
		meta:set_string("zoonami_automatic_zoom", "true")
		initialized.automatic_zoom = true
	end
	if not initialized.backpack_gui_zoom then
		meta:set_float("zoonami_backpack_gui_zoom", 1)
		initialized.backpack_gui_zoom = true
	end
	if not initialized.battle_gui_zoom then
		meta:set_float("zoonami_battle_gui_zoom", 1)
		initialized.battle_gui_zoom = true
	end
	if not initialized.battle_music_volume then
		meta:set_float("zoonami_battle_music_volume", 1)
		initialized.battle_music_volume = true
	end
	if not initialized.battle_sfx_volume then
		meta:set_float("zoonami_battle_sfx_volume", 1)
		initialized.battle_sfx_volume = true
	end
	
	meta:set_string("zoonami_initialized", core.serialize(initialized))
	
	-- Settings that are always reset to default values
	inv:set_size("zoonami_backpack_items", 12)
	meta:set_string("zoonami_music_handler", "false")
	meta:set_string("zoonami_battle_session_id", "0")
	meta:set_string("zoonami_trade_session_id", "")
	meta:set_string("zoonami_pvp_id", "")
	meta:set_string("zoonami_battle_pvp_enemy", "")
	meta:set_string("zoonami_host_battle", "")
	meta:set_string("zoonami_join_battle", "")
	meta:set_string("zoonami_backpack_page", "monsters")
end)

core.register_on_respawnplayer(function(player)
	local player_name = player:get_player_name()
	local creative_mode = core.is_creative_enabled(player_name)
	if resupply_on_respawn and not creative_mode then
		local inv = player:get_inventory()
		core.add_item(pos, inv:add_item("main", "zoonami:guide_book"))
		core.add_item(pos, inv:add_item("main", "zoonami:backpack"))
	end
end)
