local storage = core.get_mod_storage()
local effects = {}

PyuTest.STATUS_EFFECTS = {
	"speed",
	"jump_boost",
	"low_gravity"
}

PyuTest.status_effect_add = function(player, name, multiplier, length)
	effects[player][name] = multiplier

	if length ~= nil then
		core.after(length, function()
			PyuTest.status_effect_remove(player, name)
		end)
	end
end

PyuTest.status_effect_remove = function (player, name)
	effects[player][name] = false
end

PyuTest.status_effect_get = function (player, name)
	if effects[player][name] ~= false then
		return effects[player][name]
	end
	return 1
end

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

	for _, v in pairs(PyuTest.STATUS_EFFECTS) do
		if effects[name][v] == nil then
			effects[name][v] = false
		end
	end
end)

core.register_on_respawnplayer(function (player)
	local name = player:get_player_name()

	for _, v in pairs(PyuTest.STATUS_EFFECTS) do
		effects[name][v] = false
	end
end)

core.register_globalstep(function ()
	for _, v in pairs(core.get_connected_players()) do
		local name = v:get_player_name()

		-- speed calculation
		local speed_multiplier = 1 * PyuTest.status_effect_get(name, "speed")
		local sprint_addition = 0.35

		if v:get_player_control().aux1 and PyuTest.hunger_get(name) > 6 then
			speed_multiplier = speed_multiplier + sprint_addition
			PyuTest.hunger_multiplier(name, 4)
		else
			PyuTest.hunger_multiplier(name, 1)
		end
		-- end speed calculation

		local jump_boost = 1 * PyuTest.status_effect_get(name, "jump_boost")
		local gravity = 1 * PyuTest.status_effect_get(name, "low_gravity")

		v:set_physics_override({
			speed = 1 * speed_multiplier,
			jump = 1 * jump_boost,
			gravity = 1 * gravity
		})

		local fovm = (1 + (speed_multiplier) * sprint_addition)
		v:set_fov(fovm, true, 0.15)
	end
end)

core.register_chatcommand("effect", {
	params = "add|remove <player> <effect> <time> <multiplier>",
	description = "Add or Remove <effect> from <player>",
	func = function (name, param)
		local split = param:split(" ")

		core.log(#split)
		if #split < 3 then
			core.chat_send_player(name, "Invalid syntax: " .. param)
			return
		end

		local option = split[1]
		local targets = PyuTest.chatcommand_entity_selector(name, split[2])
		local effect = split[3]

		for _, v in pairs(targets) do
			if not core.get_player_by_name(v) then
				core.chat_send_player(name, "Invalid player: " .. v)
				return
			end
		end

		if option == "add" and #split == 5 then
			local time = tonumber(split[4])
			local multiplier = tonumber(split[5])
			for _, v in pairs(targets) do
				PyuTest.status_effect_add(v, effect, multiplier, time)
			end
		elseif option == "remove" and #split == 3 then
			for _, v in pairs(targets) do
				PyuTest.status_effect_remove(v, effect)
			end
		end
	end
})
