local module = {}

local partStateModule = require(_G.Modules.PartStateModule)

function setup(this,rope,context)
	local function new(name,tab)
		local part = Instance.new(name)
		_G.Union(part,tab)
		return part
	end
	
	local node1 = rope["1"]
	local node2 = rope["2"]
	if rope.Name == "Shaft" then -- Make two universal constraints
		local constraint1 = new("UniversalConstraint",{
			Parent = node1,
			Attachment0 = new("Attachment",{
				Parent = node1
			}),
			Attachment1 = new("Attachment",{
				Parent = rope,
				WorldCFrame = node1.CFrame
			})
		})
		local constraint2 = new("UniversalConstraint",{
			Parent = node2,
			Attachment0 = new("Attachment",{
				Parent = node2
			}),
			Attachment1 = new("Attachment",{
				Parent = rope,
				WorldCFrame = node2.CFrame
			})
		})
	elseif rope.Name == "Rope" or rope.Name == "Rod2" then
		rope.Transparency = 1
		rope.CanCollide = false
		rope.Massless = true
		
		local name
		if rope.name == "Rope" then name = "RopeConstraint" end
		if rope.Name == "Rod2" then name = "RodConstraint" end
		local constraint = new(name,{
			Parent = rope,
			Attachment0 = new("Attachment",{
				Parent = node1
			}),
			Attachment1 = new("Attachment",{
				Parent = node2
			}),
			Visible = true,
			Thickness = rope.Size.Y
		}) 
		if rope.Length.Value == 0 then rope.Length.Value = constraint.CurrentDistance end
		constraint.Length = rope.Length.Value
	end
	
	node1.CanCollide = true -- Resize and make nodes non-collide
	node2.CanCollide = true
	node1.Size = Vector3.one * rope.Size.Y
	node2.Size = node1.Size
	for index,joint in pairs(rope:GetJoints()) do -- Fix welds in new version
		if joint:IsA("WeldConstraint") then 
			local other = joint.Part0
			if joint.Part0 == rope then other = joint.Part1 end
			local closest = node1
			if (node2.Position-other.Position).Magnitude < (node1.Position-other.Position).Magnitude then closest = node2 end
			new("WeldConstraint",{
				Parent = rope,
				Part0 = closest,
				Part1 = other,
				Name = "BuiltWeldConstraint"
			})
			if index > 1 then joint:Destroy() end
		end
	end
end


function module.new(this,rope,context)
	if _G.IsServer then setup(this,rope,context) end
	return this
end

module.manifest = {
	"Rod2",
	"Rope",
	"Shaft"
}

return module
