-- Add script when player is added

game.Players.PlayerAdded:connect(addScriptAtRespawn)


local MyHook = script.Parent["Chain Hook"]
local Remote = script.Parent.RemoteEvent
local Bindable = MyHook.Talker
local Coupled = script.Parent.Coupled
local Rotator = script.Parent.Rotator.Rotator

function weld(i,j)
	local weld1 = Instance.new("Weld") 
	weld1.Name = j.Name
	weld1.Part0 = i
	weld1.Part1 = j
	weld1.C1 = j.CFrame:inverse()*i.CFrame
	weld1.Parent = j
end

function SetupDecouple(chain)
	if chain.Parent then
		Coupled.Value = true
		local b
		local a
		a = chain.AncestryChanged:connect(function(_,newpar)
			if not newpar then
				Coupled.Value = false
				a:disconnect()
				b:disconnect()
			end
		end)
		b = chain.ChildRemoved:connect(function()
			Coupled.Value = false
			a:disconnect()
			b:disconnect()
			wait()
			chain:Destroy()
		end)
	end
end

Bindable.Event:connect(function(data)
	if data["Chain"] then
		SetupDecouple(data["Chain"])
	end
end)

function couple(hook1,hook2)
	if hook1.Velocity.magnitude > 0.5 or hook2.Velocity.magnitude > 0.5 then
		return false
	end
	if (hook1.Position-hook2.Position).magnitude > 5 and (hook1.Position-hook2.Position).magnitude < 3 then
		return false
	end
	local chain = Instance.new("Part")
	chain.Material = "SmoothPlastic"
	chain.TopSurface = "Smooth"
	chain.BottomSurface = "Smooth"
	chain.BrickColor = BrickColor.DarkGray()
	chain.FormFactor = "Custom"
	chain.Name = "Chain Link Coupler"
	chain.Anchored = true
	chain.Size = Vector3.new(0.4,0.2,(hook1.Position-hook2.Position).magnitude)
	chain.CFrame = CFrame.new((hook1.CFrame*CFrame.new(-.1*hook1.Size.X,0,0)).p:Lerp((hook2.CFrame*CFrame.new(-.1*hook2.Size.X,0,0)).p,0.5),(hook2.CFrame*CFrame.new(-.1*hook2.Size.X,0,0)).p)
	weld(hook1.Parent.Rotator.Rotator,chain)
	weld(hook2.Parent.Rotator.Rotator,chain)
	chain.CanCollide = false
	chain.Parent = script.Parent
	script.Decouple:Clone().Parent = chain
	chain.Decouple.Disabled = false
	SetupDecouple(chain)
	hook2.Talker:Fire({["Chain"]=chain})
	wait(.1)
	chain.Anchored = false
	return true
end

Remote.OnServerEvent:connect(function(player,data)
	if data["Connect this"] and data["Connect this"].Name == "Chain Hook" and data["Connect this"] ~= MyHook and not Coupled.Value and not data["Connect this"].Parent.Coupled.Value then
		couple(MyHook,data["Connect this"])
	end
end)
