option explicit

!INC Local Scripts.EAConstants-VBScript

'
' This script exports a Learning Center structure to your file system. 
' You can specify the output path in the Filename property of the selected package.
' Each child Package will be exported as a folder and Artifact element's as an RTF file.
'

Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")

' Get the type of element selected in the Project Browser
dim treeSelectedType
treeSelectedType = Repository.GetTreeSelectedItemType()

Dim indexFile

sub CreateLearningCenter( package, path, fullName )
	Dim childElement
	Dim childPackage
	
	dim outFile
	outFile = path & "order.txt"
	dim objFile

	for each childElement in package.Elements
	
		dim e as EA.Element
		if not childElement.Type = "Artifact" or not childElement.Stereotype = "document" then exit for
		
		if not oFSO.FolderExists(path) then
			oFSO.CreateFolder path
		end if
		
		if IsEmpty(objFile) then
			set objFile = oFSO.CreateTextFile(outFile,True)
		end if
		
		if not childElement.SaveLinkedDocument (path & childElement.Name & ".rtf") then
				Session.Output "Error writing document: " & path & childElement.Name & ".rtf"
		end if
		objFile.Write childElement.Name & ".rtf" & vbCrLf
		
		indexFile.Write childElement.ElementGUID & "," & fullName & childElement.Name & vbCrLf
	next
	
	for each childPackage in package.Packages
	
		if not oFSO.FolderExists(path) then
			oFSO.CreateFolder path
		end if
		
		if IsEmpty(objFile) then
			set objFile = oFSO.CreateTextFile(outFile,True)
		end if
		
		CreateLearningCenter childPackage, path & childPackage.Name & "\", fullName & childPackage.Name & "\"
		
		if oFSO.FolderExists(path & childPackage.Name & "\") then
			objFile.Write childPackage.Name & "\" & vbCrLf
		end if
	next
	

	if not IsEmpty(objFile) then
		objFile.Close
	end if
end sub

select case treeSelectedType
	
	case otPackage
		' Code for when a package is selected
		dim thePackage as EA.Package
		dim thePackageElement as EA.Element
		set thePackage = Repository.GetTreeSelectedObject()
		set thePackageElement = thePackage.Element
		
		if not IsNull ( thePackageElement ) and thePackageElement.Genfile <> "" Then
			set indexFile = oFSO.CreateTextFile(thePackageElement.Genfile & "\index.txt",True)
			CreateLearningCenter thePackage, thePackageElement.Genfile & "\", thePackage.Name & "\"
			
			if not IsEmpty(indexFile) then
				indexFile.Close
			end if
		Else
			Session.Prompt "Please select a package with a valid filename property and re-run the script.", promptOK
		End If

	case else
		' Error message
		Session.Prompt "Please select a package and re-run the script.", promptOK
		
end select
	
Session.Output "Script Finished"