'#Reference {A3B5C45B-F842-44fc-A5E5-50CED69BA86E}#2.0#0#C:\Program Files\Mindjet\MindManager 6\Mm5WebExport.dll#Mm5webexport 2.0 Type Library
'#Uses "GlobalUtilities.mmbas"
Option Explicit

Sub Main

    Dim addin As Mm5WebExportAddIn
    Dim webex As WebExport
    Dim aPage As Mm5WebExportLib.Page

    Set addin = WebExportHelper.WebExportAddIn
    Set webex = addin.ActiveWebExport
    Set aPage = webex.ActivePage

    Dim topicString As String
    Dim bodyString As String
    Dim template As String
    Dim templateHeader As String
    Dim RelationshipsString As String
    Dim RelationshipsStringBoundary As String
    Dim HyperlinksAndBookmarksString As String
    Dim AttachmentsString As String
    Dim MergedString As String
    Dim DoExportRelatedLinksSection As Boolean

    Dim oneRelationshipCollection As Relationships
    Dim anotherRelationshipCollection As Relationships
    Dim oneTopic As Topic

    On Error GoTo ReportError

    DoExportRelatedLinksSection = True

    webex.Trace("Entering BoxReLinksSect.mmbas", 2)

    Set oneTopic = webex.ActiveTopic

    If DoExportRelatedSection_Links(oneTopic, webex) Then

        ' Read related section template
        template = webex.ReadFile("BoxOneReSect.htm")

        ' 1. Process relationships. First for topic itself, then for the topic boundary (if it exists)
        Set oneRelationshipCollection = oneTopic.Relationships(False)
        RelationshipsString = Process_Relationships (oneRelationshipCollection, webex)
        If oneTopic.HasBoundary = True Then
            Set anotherRelationshipCollection = oneTopic.Boundary.Relationships(False)
            RelationshipsStringBoundary = Process_Relationships (anotherRelationshipCollection, webex)
        End If

        ' 2. Process hyperlinks and bookmarks
        HyperlinksAndBookmarksString = Process_HyperlinksAndBookmarks (webex.ActiveTopic, webex)

        ' 2a. Process Attachment
		AttachmentsString = Process_Attachments (webex.ActiveTopic, webex)

        ' 3. Glue together relationship and hyperlink / bookmark strings
        MergedString = HyperlinksAndBookmarksString + RelationshipsString + RelationshipsStringBoundary + AttachmentsString

        ' Insert merged sections into the wrapper "related section" template
        bodyString = Replace(template, "#RelatedSectionHeader#", webex.GetParameter("Strings.SectionHeaders.Related"))
        bodyString = Replace(bodyString,"#RelatedItem#", MergedString)

        ' Push back the two "related sections" to the web export
        webex.PushString(bodyString)

    Else

        ' Nothing to export (no relationships / hyperlinks)
        webex.PushString("")

    End If

    webex.Trace("Exiting BoxRe.mmbas", 2)

    Exit Sub
 
ReportError:
    ProcessError(webex)
    Exit Sub
 
End Sub

Function Process_Relationships (oneRelationshipCollection As Relationships, webex As WebExport) As String

    Dim oneRelationship As Relationship
    Dim oneCallout As Topic

    Dim DoInsertLink As Boolean
    Dim IsSimpleCallout As Boolean
    Dim TheFileName As String
    Dim TheBookmark As String
    Dim i As Long

    Dim localtopicString As String
    Dim localbodyString As String
    Dim localTemplate As String
    Dim processedTemplate As String

    For Each oneRelationship In oneRelationshipCollection

        ' Assume the relationship is not to be exported
        DoInsertLink = False

        ' Determine if a link is to be inserted for this type of relationship
        DoInsertLink = DoExportRelationshipSettings(oneRelationship, webex)

        ' Process relationship item template
        If DoInsertLink Then

            ' Determine what template to use for export
            If oneRelationship.CalloutTopics(False).Count > 0 Then

                ' Determine if the relationship has an attached callout
                Set oneCallout = oneRelationship.CalloutTopics(False).Item(1)
                IsSimpleCallout = webex.IsSimpleRelationshipCallout(oneCallout)

                If IsSimpleCallout Then
                    localTemplate = webex.ReadFile("SnipHypReSimpleCoText.htm")
                                    webex.SetParameter("CustomParameter.CalloutText", "(" +  VerifyTopicText(webex, oneCallout) + ")")
                Else
                    localTemplate = webex.ReadFile("SnipHypReLinkedCoPage.htm")

                    webex.SetParameter("CustomParameter.CalloutText","")
                    webex.SetParameter("CustomParameter.CalloutHyperlinkName", VerifyTopicText(webex, oneCallout) )
                    webex.SetParameter("CustomParameter.CalloutHyperlinkTarget", "")
                    webex.SetParameter("CustomParameter.CalloutHyperlinkURL", webex.PathToUrl(webex.Pages.FindPage(oneCallout).FileName))
                End If

            Else

                ' No callouts, read "simple" template
                localTemplate = webex.ReadFile("SnipHypReSimpleCoText.htm")

                ' No callout text to export
                webex.SetParameter("CustomParameter.CalloutText","")

            End If

            ' Process all commands and parameters
            ProcessString webex, localTemplate

            ' Our new hyperlink to merge into the related section body item template
            localbodyString = localbodyString + localTemplate

        Else

            ' No link for this relationship type
            localbodyString = localbodyString

        End If

    Next

    ' Assign return value to function name - this is VBA's "return value" concept
    Process_Relationships = localbodyString

End Function

Function Process_HyperlinksAndBookmarks (oneTopic As Topic, webex As WebExport) As String

    Dim localtopicString As String
    Dim localbodyString As String
    Dim localTemplate As String
    Dim processedTemplate As String
    Dim customIconFileName As String

    Dim oneIcon As Icon
    Dim oneIconCollection As Icons
    Dim oneHyperlink As Hyperlink

    Dim theUrl As String
    Dim theText As String
    Dim theTarget As String

    ' Don't process topic if it doesn't have any hyperlinks / bookmarks
    If oneTopic.HasHyperlink Then

        Set oneHyperlink = oneTopic.Hyperlink

        webex.UrlFromHyperlink(oneHyperlink, theUrl, theText, theTarget)
        
        ' If we could resolve the hyperlink to a valid URL
        If Len(theUrl) > 0 Then

            webex.SetParameter("CustomParameter.HyperlinkName", theText)
            webex.SetParameter("CustomParameter.HyperlinkURL", theUrl)
            webex.SetParameter("CustomParameter.HyperlinkTarget", theTarget)
           
            ' if this is a local bookmark
            If oneHyperlink.Address = "" Then
                ' read bookmark template
                localTemplate = webex.ReadFile("SnipBookmarkLink.htm")
            Else
                ' read hyperlink template
                localTemplate = webex.ReadFile("SnipHypRe.htm")

                ' Determine hyperlink file name
                Set oneIconCollection = oneTopic.Icons(True)
                For Each oneIcon In oneIconCollection
                    ' if we found an icon for the hyperlink
                    If oneIcon.Type = mmIconTypeAutomaticHyperlink Then
                    
                        ' create a name that is unique for this page and topic
                        customIconFileName =   RelativeMapMarkerPath(webex, webex.Pages.FindPage(oneTopic).BaseFilename _
                                             + oneIcon.Name _
                                             + webex.TopicIdForExport(oneTopic))
                        
                        ' save the icon in a file
                        oneIcon.Save(webex.FullExportFilename(customIconFileName),mmGraphicTypeGif)
                        
                        ' we're done
                        Exit For
                    End If
                Next
                
                ' remember our icon filename for substitution back in the page
                webex.SetParameter("CustomParameter.CodeFileName", webex.PathToUrl(customIconFileName))

            End If
           
            ' Process all commands and parameters
            ProcessString webex, localTemplate

            ' Our new hyperlink to merge into the related section body item template
            processedTemplate = localTemplate

            ' Our merged string to write back
            localbodyString = processedTemplate
        
        End If

    Else

       ' No link for this relationship type, hence we push back nothing
       localbodyString = ""

    End If

    ' Assign return value to function name - this is VBA's "return value" concept
    Process_HyperlinksAndBookmarks = localbodyString

End Function

Function Process_Attachments (oTopic As Topic, webex As WebExport) As String

	Dim processedBodyString As String

	If oTopic.Attachments.Count > 0 Then

		Dim localTemplate As String
		Dim theExtension As String
		Dim theUrl As String
		Dim theText As String
		Dim absoluteIconPath As String
		Dim relativeIconPath As String
		Dim oAttachment As Attachment

		For Each oAttachment In oTopic.Attachments

			' Retrieve url from attachement
			webex.UrlFromAttachment(oAttachment, theUrl)

			If Len(theUrl) > 0 Then

				' Retrieve extension from filename
				theExtension = GetExtension(oAttachment.FileName)

				' Retrieve tet from
				theText = oAttachment.FileName

				' Create icon path
				relativeIconPath = RelativeMapMarkerPath(webex, theExtension + "icon")
				absoluteIconPath = webex.FullExportFilename(relativeIconPath)

				' Save icon path
				Utilities.SaveImageForExtension(theExtension, absoluteIconPath, mmGraphicTypeGif, 16, 16)

				' read attachment template
                localTemplate = webex.ReadFile("SnipHypAttach.htm")

				' Set up parameters
				webex.SetParameter("CustomParameter.AttachmentName", theText)
            	webex.SetParameter("CustomParameter.AttachmentURL", theUrl)

				' remember our icon filename for substitution back in the page
                webex.SetParameter("CustomParameter.AttachmentIconPathName", webex.PathToUrl(relativeIconPath))

			End If

			' Process all commands and parameters
        	ProcessString webex, localTemplate

			processedBodyString = processedBodyString + localTemplate

		Next
	End If

	Process_Attachments = processedBodyString
End Function

Function GetExtension(pathAndFilename As String)
	Dim fileName As String
	Dim reverseString As String
	Dim searchString As String
	Dim nIndex As Integer

	fileName = pathAndFilename
	searchString = "."
	reverseString = StrReverse(fileName)

	nIndex = InStr(1, reverseString, searchString)

	If nIndex >= 1 Then
		If nIndex <= Len(fileName) Then
			GetExtension = Right(fileName, nIndex - 1)
		Else
			GetExtension = ""
		End If
	Else
		GetExtension = ""
	End If
End Function
