-- Will apply a body part given the r15Folder and the r6Folder for that body part.

local function applyBodyPart(character, r15Folder, r6Folder)
    local humanoid = character:FindFirstChild("Humanoid")
    if humanoid.RigType == Enum.HumanoidRigType.R15 then
		for _, part in pairs(r15Folder:GetChildren()) do
            local oldPart = character:FindFirstChild(part.Name)
			if (oldPart) then
	            part:Clone().Parent = character
	            oldPart.Name = ""
	            oldPart:Destroy()
			end
        end
        -- Rebuild the rig
        -- Note: if applying many body parts at once it is more efficient to call this after applying them all
        buildRigFromAttachments(nil, character.HumanoidRootPart)
    else
        for _, characterMesh in pairs(r6Folder:GetChildren()) do
            local oldCharacterMesh = getOldCharacterMesh(character, characterMesh)
            if oldCharacterMesh then
                oldCharacterMesh:Destroy()
            end
            characterMesh.Parent = character
        end
    end
end

local AssetService = game:GetService("AssetService")
local InsertService = game:GetService("InsertService")

function DressCharacter(character, packageId, allowTools)
	local PackageIds = AssetService:GetAssetIdsForPackage(packageId)
	local Humanoid = character:FindFirstChild("Humanoid")
	allowTools = (allowTools or false)
	
	for _,AssetId in pairs(PackageIds) do
		local Insert = InsertService:LoadAsset(AssetId)
		
		for _,Object in pairs(Insert:GetChildren()) do
			if (Object:IsA("Folder") and Object.Name == "R15") then
				applyBodyPart(character, Object, nil)
			elseif (Object:IsA("Tool") and allowTools) then
				Humanoid:EquipTool(Object)
			elseif (Object:IsA("Accessory") or Object:IsA("Hat")) then
				Humanoid:AddAccessory(Object)
			end
		end
		
		Insert:Destroy()
	end
	
	return true
end

return DressCharacter
