-- Variables

local inputBeganHandle = nil

local function OnCharacterAdded(character)
	
	local humanoid = character:WaitForChild("Humanoid")
	
	-- Listen for inputs from the local player
	inputBeganHandle = UserInputService.InputBegan:Connect(function(inputObject)
		
		local humanoidState = humanoid:GetState()
		-- Can't do any equipment management if you're dead.
		if humanoidState == Enum.HumanoidStateType.Dead then return end
		
		-- [Q] to swap weapons
		if inputObject.KeyCode == Enum.KeyCode.Q then
			-- Inform the server that we want to swap our weapons
			APIEquipment.SwapWeapons()
		elseif inputObject.KeyCode == Enum.KeyCode.G then
			
			local currentlyEquippedTool = APIEquipment.GetEquippedToolFromPlayer(Local_Player)
			
			local throwableTool = APIEquipment.GetThrowableFromPlayer(Local_Player)
			
			-- Don't swap to the grenade if we're already holding the grenade
			if throwableTool == currentlyEquippedTool then return end
			
			local throwableDefinition = APIEquipment.GetWeaponDefinitionFromTool(throwableTool)
			local throwableRuntime = APIEquipment.GetLocalCurrentWeaponRuntimeData(throwableDefinition)
			
			-- Don't allow throwing of grenades if they're out.
			if throwableRuntime:IsEmpty() then return end

			APIEquipment.SwapToThrowable()
		end
	end)
	
	-- Don't allow weapon switching when the player has died.
	humanoid.Died:Connect(function()
		if inputBeganHandle then
			inputBeganHandle:Disconnect()
		end
	end)
	
end

local function OnCharacterRemoved()
	-- Clear input handle when the character is not existing
	if inputBeganHandle then
		inputBeganHandle:Disconnect()
	end
end



if Local_Player.Character then
	OnCharacterAdded(Local_Player.Character)
end

Local_Player.CharacterAdded:Connect(OnCharacterAdded)

Local_Player.CharacterRemoving:Connect(OnCharacterRemoved)
