option explicit

!INC Local Scripts.EAConstants-VBScript

'
' Example illustrating how to add a Model or a Package.
' 
' Related APIs
' =================================================================================
' Package API - http://www.sparxsystems.com/enterprise_architect_user_guide/12.1/automation_and_scripting/package_2.html
' Element API - http://www.sparxsystems.com/enterprise_architect_user_guide/12.1/automation_and_scripting/element2.html
' Repository API - http://www.sparxsystems.com/enterprise_architect_user_guide/12.1/automation_and_scripting/repository3.html
'
sub ManagePackagesExample()

	' Show the script output window
	Repository.EnsureOutputVisible "Script"

	dim i, newModelID

	Session.Output( "VBScript MANAGE PACKAGES EXAMPLE" )
	Session.Output( "=======================================" )
	
	' Create a new model node
	dim newModel as EA.Package
	set newModel = Repository.Models.AddNew( "AdvancedModel", "" )
	newModel.Update()
	Repository.Models.Refresh()
	
	newModelID = newModel.PackageID
	Session.Output( "Added new model: " & newModel.Name & _
		" (PackageID=" & newModelID & ")" )
	
	' ==================================================
	' ADD A SUBPACKAGE TO THE MODEL
	' ==================================================
	dim packages as EA.Collection
	set packages = newModel.Packages
	
	dim subPackage as EA.Package
	set subPackage = packages.AddNew( "SubPackage", "Class" )
	subPackage.Update()
	
	' GetElement returns the underlying element representation of the package
	' The initial Update() of the package must be called before we can access the
	' underlying element.
	dim packageMetaElement as EA.Element
	set packageMetaElement = subPackage.Element
	
	' Set the package's stereotype
	packageMetaElement.Stereotype = "system"
	subPackage.Update()
	
	packages.Refresh()
	
	Session.Output( "Added subpackage '" & subPackage.Name & _
		"' under model '" & newModel.Name & "'" )
	
	set packageMetaElement = nothing
	set subPackage = nothing
	set newModel = nothing
	
	' List all models in the collection, deleting the one we added
	for i = 0 to Repository.Models.Count - 1
		dim currentModel as EA.Package
		set currentModel = Repository.Models.GetAt( i )
		Session.Output( "Model: " & currentModel.Name )
		
		' If the model is the one we just added, then delete it
		if currentModel.PackageID = newModelID then
			Repository.Models.DeleteAt i, false
			Session.Output( "Deleted model " & currentModel.Name & _
				" (PackageID=" & currentModel.PackageID & ")" )
		end if
	next
	
	Session.Output( "Done!" )
	
end sub

ManagePackagesExample
