Imports Plumtree.Remote.PRC.Collaboration.Project
Imports Plumtree.Remote.PRC.Collaboration.Document
Imports Plumtree.Remote.PRC.RemoteSessionFactory

Imports System
Imports System.IO

'To change this example to run on any collaboration server, be sure to change the endpointURL, username and password
'which are all set at the beginning of the main method.
'The example program also expects that "C:\report.doc" and "C:\report2.doc" exist.  
'Create these files or change the filenames referred to below to run the program.

Public Class DocumentCommandLineExample

    Shared documentManager As IDocumentManager
    Shared projectManager As IProjectManager

    Public Shared Sub Main()

        'Change the values below to match your configuration
        Dim endpointURL As New Uri("http://localhost:8080/ptapi/services/QueryInterfaceAPI")
        Dim username As New String("Administrator")
        Dim password As New String("")

        'Connect to create a session & retrieve the document manager
        Dim remoteSession As Plumtree.Remote.PRC.IRemoteSession = Plumtree.Remote.PRC.RemoteSessionFactory.GetExplicitLoginContext(endpointURL, username, password)
        documentManager = remoteSession.GetCollaborationFactory().GetDocumentManager()
        projectManager = remoteSession.GetCollaborationFactory().GetProjectManager()

        'Create a project to work in
        Dim exampleProject As IProject = projectManager.CreateProject("document example project", "example document project")
        'Store it
        exampleProject.Store()

        '*** Create new objects ***
        'Create a new folder
        Dim newFolder As IDocumentFolder = CreateAndInsertNewFolder(exampleProject, "example folder")

        'Create a new document
        Dim newDocument As IDocument = CreateAndInsertNewDocument(newFolder)

        '*** Edit the document ***
        'Check it out for editing
        documentManager.CheckOutDocument(newDocument)

        'We can query here, and get the checked out document
        Dim checkedOutDocuments() As IDocument = FindCheckedOutDocumentsInProject(exampleProject)

        'Check in a new version
        CheckInNewDocumentVersion(newDocument)

        'Retrieve the content back, and store it to a file
        StoreDocumentContent(newDocument)

        'Create a another folder...
        Dim newFolder2 As IDocumentFolder = CreateAndInsertNewFolder(exampleProject, "example folder 2")

        'Then copy the new document to it
        CopyDocumentToFolder(newDocument, newFolder, newFolder2)

        'We can query here, and get the two created folders
        Dim rootFolders() As IDocumentFolder = FindFirstLevelFolders(exampleProject)

        '*** Remove the objects ***
        'Remove the document
        documentManager.RemoveDocument(newDocument)

        'Remove the folder
        documentManager.RemoveDocumentFolder(newFolder)

        'Remove the main project (which removes all contained objects)
        projectManager.RemoveProject(exampleProject)
    End Sub

    Public Shared Function FindFirstLevelFolders(ByVal project As IProject) As IDocumentFolder()
        'Create the new query filter
        Dim filter As IDocumentFolderFilter = documentManager.CreateDocumentFolderFilter()

        'Set to order by name
        Dim nameOrder As DocumentFolderQueryOrder = New DocumentFolderQueryOrder(DocumentFolderAttributes.Name, True)
        Dim orders() As DocumentFolderQueryOrder = {nameOrder}
        filter.QueryOrders = orders

        'To find folders in a project, we must look in the top level folder
        Dim topLevelFolder As IDocumentFolder = documentManager.GetTopLevelFolder(project)
        Dim foundFolders As IDocumentFolder() = documentManager.QueryFolders(topLevelFolder, filter)

        Return foundFolders
    End Function

    Public Shared Function FindCheckedOutDocumentsInProject(ByVal project As IProject) As IDocument()
        'Create the new query filter
        Dim filter As IDocumentFilter = documentManager.CreateDocumentFilter()

        'Set it to only search for checked-out documents
        filter.FilterType = DocumentFilterTypes.CheckedOutByCurrentUser

        'Set to order by size, then last modified date
        Dim sizeOrder As DocumentQueryOrder = New DocumentQueryOrder(DocumentAttributes.NumBytes, True)
        Dim lastModifiedOrder As DocumentQueryOrder = New DocumentQueryOrder(DocumentAttributes.LastModified, True)
        Dim orders() As DocumentQueryOrder = {sizeOrder, lastModifiedOrder}
        filter.QueryOrders = orders

        'Perform query
        Dim foundDocuments() As IDocument = documentManager.QueryDocuments(project, filter)
        Return foundDocuments

    End Function

    Public Shared Sub CopyDocumentToFolder(ByVal documentToCopy As IDocument, ByVal sourceFolder As IDocumentFolder, ByVal targetFolder As IDocumentFolder)
        'Documents to copy
        Dim documentsToCopy() As IDocument = {documentToCopy}

        'We won't copy any folders
        Dim foldersToCopy() As IDocumentFolder = {}

        'Copy the document, inheriting the security from the target folder
        documentManager.CopyToFolder(sourceFolder, targetFolder, documentsToCopy, foldersToCopy, True, "copied from original sample folder")
    End Sub

    Public Shared Sub CheckInNewDocumentVersion(ByVal originalDocument As IDocument)

        'Open an inputstream for the document contents
        Dim fileInputStream As Stream = File.OpenRead("c:\\report2.doc")

        'Check in the new version
        documentManager.CheckInDocument(originalDocument, "this is an updated version of the example document", fileInputStream, "en", False)
    End Sub

    Public Shared Function CreateAndInsertNewDocument(ByVal containingFolder As IDocumentFolder) As IDocument
        'Create the document
        Dim newDocument As IDocument = documentManager.CreateNewDocument("my new document", "this is a test document created by the samples")

        'Set optional properties
        newDocument.Author = "joe bloggs"

        'Set content-type
        newDocument.ContentType = "text/vnd.ms-word"

        'Open an inputstream for the document contents
        Dim fileInputStream As FileStream = File.OpenRead("c:\\report.doc")

        'Insert the document, inheriting the containing folder's security
        Dim storedDocument As IDocument = documentManager.InsertNewDocument(containingFolder, newDocument, "initial check-in", fileInputStream, "en", True)

        Return storedDocument
    End Function

    Public Shared Function CreateAndInsertNewFolder(ByVal containingProject As IProject, ByVal name As String) As IDocumentFolder
        'Create the folder
        Dim newFolder As IDocumentFolder = documentManager.CreateNewFolder(name, "this is a test folder created by the examples")

        'Could now set optional properties such as security on newFolder before store...

        'Get the top level folder of the project to insert the document into
        Dim topLevelFolder As IDocumentFolder = documentManager.GetTopLevelFolder(containingProject)

        'Insert the folder, inheriting the top level folder's security
        Dim storedFolder As IDocumentFolder = documentManager.InsertNewFolder(topLevelFolder, newFolder, True)

        Return storedFolder
    End Function

    Public Shared Sub StoreDocumentContent(ByVal toStore As IDocument)
        'Generate a file name to store the content to
        Dim nameToUse As String = toStore.Name & ".doc"

        'Create an output stream to store the data
        Dim fileOutputStream As Stream = File.OpenWrite(nameToUse)

        Dim documentContentStream As Stream

        Try
            'Get the content stream
            documentContentStream = toStore.GetContentAsInputStream()

            'Pump it out to a file
            Dim buf(32 * 1024) As Byte
            Dim read As Integer = documentContentStream.Read(buf, 0, buf.Length)

            While (read > 0)
                fileOutputStream.Write(buf, 0, read)
                read = documentContentStream.Read(buf, 0, buf.Length)
            End While

        Finally 'make sure the stream is closed

            documentContentStream.Close()
            fileOutputStream.Close()
        End Try
    End Sub
End Class
