local S = minetest.get_translator("hades_commands")

minetest.register_chatcommand("hp", {
	privs = {server=true},
	--~ command syntax for '/hp' command
	params = S("[<player>] <value>"),
	description = S("Set health points of player or yourself"),
	func = function(name, param)
		if minetest.settings:get_bool("enable_damage") == false then
			return false, S("Not possible, damage is disabled.")
		end
		local targetname, hp = string.match(param, "(%S+) (%S+)")
		if not targetname then
			hp = param
			targetname = name
		end
		local target = minetest.get_player_by_name(targetname)
		hp = minetest.parse_relative_number(hp, target:get_hp())
		if not hp then
			return false, S("Invalid health!")
		end
		if target == nil or not target:is_player() then
			return false, S("Player @1 does not exist.", targetname)
		end
		local hp_max = target:get_properties().hp_max
		if hp > hp_max then
			hp = hp_max
		end
		if name == targetname then
			hades_death_messages.player_damage(target, S("A death wish"))
		else
			-- You took damage from "a higher power" ;-)
			hades_death_messages.player_damage(target, S("A higher power"))
		end
		target:set_hp(hp, {type="set_hp", from="mod", _custom_reason="hp_command"})
		return true
	end,
})

-- Extend /kill command to show death message
minetest.register_on_chatcommand(function(name, command, params)
	if command == "kill" then
		local targetname = params
		if targetname == "" then
			targetname = name
		end
		local target = minetest.get_player_by_name(targetname)
		-- /kill is not supported for players in simulation because we cannot cleanly handle this situation
		-- so far.
		-- TODO: Allow /kill for players in simulation; this should kill them in the in-game "reality"
		if hades_simulation.is_in_simulation(target) then
			minetest.chat_send_player(name, S("@1 is in a simulation and the “/kill” cannot be used right now. Use “/hp” instead", targetname))
			return true
		end
		if not target or not target:is_player() then
			return
		end
		if name == targetname then
			hades_death_messages.player_damage(target, S("A death wish"))
		else
			hades_death_messages.player_damage(target, S("A higher power"))
		end
	end
end)
