-- Item usage system

function FindToolInHand()
	if players.LocalPlayer.Character and players.LocalPlayer.Character:FindFirstChild("Humanoid") and players.LocalPlayer.Character:FindFirstChild("HumanoidRootPart") then
		return players.LocalPlayer.Character:FindFirstChildOfClass("Tool")
	end
end

function Attack()
	local tool = FindToolInHand()
	if tool and attackCooldown == false then
		if require(itemFunctions)[tool.ItemType.Value] then
			attackCooldown = true
			require(itemFunctions)[tool.ItemType.Value](tool)
			attackCooldown = false
		else
			warn('Tried to use weapon attack "' .. tool.ItemType.Value .. '" but failed to find a matching function in ' .. itemFunctions:GetFullName())
		end
	end
end

function StrongAttack()
	local tool = FindToolInHand()
	if tool and strongAttackCooldown == false and attackCooldown == false then
		if require(weaponStrongAttacks)[tool.ItemType.Value] then
			strongAttackCooldown = true
			require(weaponStrongAttacks)[tool.ItemType.Value](tool)
			strongAttackCooldown = false
		else
			warn('Tried to use weapon strong attack "' .. tool.ItemType.Value .. '" but failed to find a matching function in ' .. weaponStrongAttacks:GetFullName())
		end
	end
end

mouse.Button1Down:Connect(function() -- Left click attack
	if game:GetService("UserInputService").KeyboardEnabled == false then -- Player is probably on mobile
		wait() -- Mobile mouse position takes a frame to update for some reason
		local lastMousePosition = Vector2.new(mouse.X, mouse.Y)
		wait(0.25)
		if math.abs(mouse.X - lastMousePosition.X) > 25 or math.abs(mouse.Y - lastMousePosition.Y) > 25 then -- Return if the touch position didn't stay in relatively the same place
			return
		end
	end
	Attack()
end)

mouse.Button2Down:Connect(function() -- Right click attack
	rightMouseDown = true
	wait(0.15)
	if rightMouseDown == false then -- People use the right mouse button to move the camera, so we need to get hacky to detect a click
		StrongAttack()
	end
end)

mouse.Button2Up:Connect(function()
	rightMouseDown = false
end)

game:GetService("UserInputService").TouchLongPress:Connect(StrongAttack) -- Mobile strong attack
game:GetService("UserInputService").InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.ButtonL2 then
		StrongAttack()
	end
end)
