--[[
	AntiGravityCoil
	Tool that isn't Tree'd
	Phoenix
]]


local Tool = script.Parent 
local Player = Tool.Parent.Parent
local Died = nil
local Equipped = false

local IsAlive = function()
	if Player.Character then
		if Player.Character:FindFirstChild("Humanoid") then
			if Player.Character:FindFirstChild("Humanoid").Health > 0 then
				return true
			end
		end
	end

	return false
end


local Humanoid = function()
	if Player.Character then
		if Player.Character:FindFirstChild("Humanoid") then
			return Player.Character:FindFirstChild("Humanoid")
		end
	end
end


local Weld = function(From, To)
	local WeldIns = Instance.new("WeldConstraint")
	WeldIns.Part0 = From
	WeldIns.Part1 = To
	WeldIns.Parent = From
	WeldIns.Name = "Weld"
end

local Welding = function(WeldTree, OverrideCenter)
	local Center = nil
	
	if OverrideCenter == nil then
		if WeldTree:FindFirstChildOfClass("MeshPart") then
			Center = WeldTree:FindFirstChildOfClass("MeshPart")
		elseif WeldTree:FindFirstChildOfClass("Part") then
			Center = WeldTree:FindFirstChildOfClass("Part")
		elseif WeldTree:FindFirstChildOfClass("UnionOperation") then
			Center = WeldTree:FindFirstChildOfClass("UnionOperation")
		end
	else
		Center = OverrideCenter
	end

	if Center ~= nil then
		for Index, ToWeld in pairs(WeldTree:GetDescendants()) do
			if ToWeld:IsA("BasePart") then
				Weld(ToWeld, Center)
			end
		end
	else
		print("Could not get a part to weld to! Attempted ".. tostring(WeldTree:GetFullName()).. " By: ".. script:GetFullName())
	end
end


local Enable = function()
	game:GetService("ServerScriptService").Server.Events.ZGSet:Fire(Player, true, false)
end


local Disable = function()
	game:GetService("ServerScriptService").Server.Events.ZGSet:Fire(Player, false, false)
end


Tool.Equipped:Connect(function()
	if Equipped == true then
		return
	end
	
	if IsAlive() == true then
		Equipped = true
		
		Died = Humanoid().Died:Connect(function()
			Disable()
			Died:Disconnect()
			Died = nil
		end)

		Enable()

		Tool.Handle.CoilSound:Play()
	end
end)

Tool.Unequipped:Connect(function()
	if Equipped == false then
		return
	end
	
	Equipped = false
	
	if Died ~= nil then
		Died:Disconnect()
		Died = nil
	end

	Disable()
end)

Welding(Tool.Model, Tool.Handle)
