--returns the wielding player of this tool

function getPlayer()
	local char = Tool.Parent
	return game:GetService("Players"):GetPlayerFromCharacter(Character)
end

local function setTransparency(object: Instance, transparency: number)
	for i, v in ipairs(object:GetDescendants()) do
		if v:IsA("BasePart") then
			v.Transparency = transparency
		end
	end
end

local function setCollision(object: Instance, collision: boolean)
	for i, v in ipairs(object:GetDescendants()) do
		if v:IsA("BasePart") then
			v.CanCollide = collision
		end
	end
end

function Toss(direction)
	local handlePos = Vector3.new(Tool.Handle.Position.X, 0, Tool.Handle.Position.Z)
	local spawnPos = Character.Head.Position

	spawnPos = spawnPos + (direction * 5)

	local Object = Tool.Handle:Clone()

	local PinClone = Object.Details.Top.Handle.Pin:Clone()
	PinClone.CanCollide = true
	PinClone.Archivable = false
	PinClone.Parent = workspace

	game:GetService("Debris"):AddItem(PinClone, 5)

	Object.Details.Top.Handle.Pin.Transparency = 1

	setTransparency(Tool.Handle.Details, 1)

	setCollision(Object.Details, true)

	Object.Parent = workspace
	Object.Fuse:Play()

	Object.Swing.Pitch = Random.new():NextInteger(90, 110) / 100
	Object.Swing:Play()

	Object.CFrame = Tool.Handle.CFrame
	Object.Velocity = (direction * AttackVelocity) + Vector3.new(0, AttackVelocity / 7.5, 0)
	Object.Trail.Enabled = true

	local rand = 11.25
	Object.RotVelocity = Vector3.new(
		Random.new():NextNumber(-rand, rand),
		Random.new():NextNumber(-rand, rand),
		Random.new():NextNumber(-rand, rand)
	)
	Object:SetNetworkOwner(getPlayer())

	local tag = Instance.new("ObjectValue")
	tag.Value = getPlayer()
	tag.Name = "creator"
	tag.Parent = Object

	local ScriptClone = DamageScript:Clone()
	ScriptClone.Parent = Object
	ScriptClone.Disabled = false
end

PowerRemote.OnServerEvent:Connect(function(player, Power)
	local holder = getPlayer()
	if holder ~= player then
		return
	end

	AttackVelocity = Power
end)

TossRemote.OnServerEvent:Connect(function(player, mousePosition)
	local holder = getPlayer()
	if holder ~= player then
		return
	end

	if Cooldown.Value == true then
		return
	end
	Cooldown.Value = true

	if Humanoid and Humanoid.RigType == Enum.HumanoidRigType.R15 then
		TossRemote:FireClient(getPlayer(), "PlayAnimation", "Animation")
	end
	local targetPos = mousePosition.p
	local lookAt = (targetPos - Character.Head.Position).unit

	Toss(lookAt)
	Tool:Destroy()

	--task.wait(CooldownTime)
	--setTransparency(Tool.Handle.Details, 0)

	--Cooldown.Value = false
end)

Tool.Equipped:Connect(function()
	Character = Tool.Parent
	Humanoid = Character:FindFirstChildOfClass("Humanoid")
end)

Tool.Unequipped:Connect(function()
	Character = nil
	Humanoid = nil
end)
