Imports System.ServiceModel
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.EDMI.API
Imports DevExpress.XtraEditors
Imports DevExpress.XtraEditors.Controls
Imports System.IO

Public Class Form1
    Private _Channel As EDMIServiceReference.IEDMIServiceChannel

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim oLogConfig As New LogConfig(LogConfig.PathType.Temp)
        Dim oChannelFactory As New ChannelFactory(Of EDMIServiceReference.IEDMIServiceChannel)(
            Channel.GetBinding(TcpClientCredentialType.Windows),
            "net.tcp://172.24.12.39:9000/DigitalData/Services/Main")
        _Channel = oChannelFactory.CreateChannel()
        _Channel.Open()

        DocumentViewer1.Init(oLogConfig, "21182889975216572111813147150675976632")
    End Sub

    Private Sub AddLogMessage(Message As String)
        listboxLog.Items.Add(Message)
        listboxLog.MakeItemVisible(listboxLog.Items.Count - 1)
    End Sub

    Private Sub ButtonSelectFiles_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles ButtonSelectFiles.ItemClick
        Dim oDialog As New OpenFileDialog() With {
            .Multiselect = True,
            .CheckFileExists = True
        }
        Dim oResult = oDialog.ShowDialog()

        If oResult = DialogResult.OK Then
            For Each oFileName In oDialog.FileNames
                listboxFiles.Items.Add(oFileName)
            Next
        End If
    End Sub

    Private Async Sub ButtonImportFiles_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles ButtonImportFiles.ItemClick
        Dim oFiles As New List(Of String)
        Dim oSWTotal As New Stopwatch()
        oSWTotal.Start()

        For Each oItem As String In listboxFiles.Items
            Dim oSW As New Stopwatch()
            oSW.Start()
            Dim oFileName As String = oItem
            Dim oFileInfo As New FileInfo(oFileName)

            AddLogMessage($"Importing {oFileInfo.Name}... ({FormatBytes(oFileInfo.Length)})")

            Dim oContents As Byte() = New Byte(oFileInfo.Length) {}

            Using oStream As New FileStream(oFileName, FileMode.Open)
                Await oStream.ReadAsync(oContents, 0, oFileInfo.Length)
            End Using

            Dim oResult As EDMIServiceReference.DocumentResult = Await _Channel.ImportFileAsync(oFileInfo.Name, oContents, Environment.UserName)
            If oResult.OK Then
                AddLogMessage($"File [{oFileInfo.Name}] with Id [{oResult.Document.FileId}] imported!")
            Else
                AddLogMessage($"Import Error: {oResult.ErrorMessage}")
            End If
            oSW.Stop()
            AddLogMessage($"Import Time: {FormatTime(oSW.ElapsedMilliseconds)}")
            AddLogMessage("")
        Next

        oSWTotal.Stop()
        AddLogMessage($"Total Time: {FormatTime(oSWTotal.ElapsedMilliseconds)}")
    End Sub

    Private Sub buttonClearLog_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles buttonClearLog.ItemClick
        listboxLog.Items.Clear()
    End Sub

    Private Sub buttonClearFiles_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles buttonClearFiles.ItemClick
        listboxFiles.Items.Clear()
    End Sub

    Public Function FormatTime(Milliseconds As Integer) As String
        If Milliseconds < 1000 Then
            Return Milliseconds & " ms"
        Else
            Return (Milliseconds / 1000) & " s"
        End If
    End Function

    Dim DoubleBytes As Double
    Public Function FormatBytes(ByVal BytesCaller As ULong) As String

        Try
            Select Case BytesCaller
                Case Is >= 1099511627776
                    DoubleBytes = CDbl(BytesCaller / 1099511627776) 'TB
                    Return FormatNumber(DoubleBytes, 2) & " TB"
                Case 1073741824 To 1099511627775
                    DoubleBytes = CDbl(BytesCaller / 1073741824) 'GB
                    Return FormatNumber(DoubleBytes, 2) & " GB"
                Case 1048576 To 1073741823
                    DoubleBytes = CDbl(BytesCaller / 1048576) 'MB
                    Return FormatNumber(DoubleBytes, 2) & " MB"
                Case 1024 To 1048575
                    DoubleBytes = CDbl(BytesCaller / 1024) 'KB
                    Return FormatNumber(DoubleBytes, 2) & " KB"
                Case 0 To 1023
                    DoubleBytes = BytesCaller ' bytes
                    Return FormatNumber(DoubleBytes, 2) & " bytes"
                Case Else
                    Return ""
            End Select
        Catch
            Return ""
        End Try

    End Function

    Private Async Sub ButtonLoadFile_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles ButtonLoadFile.ItemClick
        Try
            Dim oSWTotal As New Stopwatch()
            oSWTotal.Start()

            If TextboxObejctId.EditValue = "" Then
                MsgBox("Please enter an object id!", MsgBoxStyle.Exclamation, "Uh oh!")
            End If

            Dim oObjectId As Integer = TextboxObejctId.EditValue

            Dim oResponse = Await _Channel.GetFileByObjectIdAsync(New EDMIServiceReference.DocumentStreamRequest() With {.ObjectId = oObjectId})
            Dim oMemoryStream As New MemoryStream()
            oResponse.FileContents.CopyTo(oMemoryStream)
            oMemoryStream.Position = 0

            DocumentViewer1.LoadFile(oResponse.FileName, oMemoryStream)

            oSWTotal.Stop()
            AddLogMessage($"File [{oResponse.FileName}] loaded: [{FormatTime(oSWTotal.ElapsedMilliseconds)}]")
        Catch ex As FaultException
            MsgBox(ex.Reason.ToString, MsgBoxStyle.Critical, "Error from Service")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Uh oh!")
        End Try
    End Sub

    Private Async Sub BarButtonItem2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem2.ItemClick
        Try
            Dim oResult = Await _Channel.ListFilesForUserAsync()
            BindingSource1.DataSource = oResult.Datatable
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Uh oh!")
        End Try
    End Sub

    Private Async Sub BindingSource1_CurrentChanged(sender As Object, e As EventArgs) Handles BindingSource1.CurrentChanged
        Dim oRow As DataRow = GridView1.GetFocusedDataRow()

        If oRow Is Nothing Then
            Exit Sub
        End If

        Try
            Dim oSWTotal As New Stopwatch()
            oSWTotal.Start()

            Dim oObjectId As Int64 = oRow.Item("IDB_OBJ_ID")
            Dim oResponse = Await _Channel.GetFileByObjectIdAsync(New EDMIServiceReference.DocumentStreamRequest() With {.ObjectId = oObjectId})
            Dim oMemoryStream As New MemoryStream()
            oResponse.FileContents.CopyTo(oMemoryStream)
            oMemoryStream.Position = 0

            DocumentViewer1.LoadFile(oResponse.FileName, oMemoryStream)

            oSWTotal.Stop()
            AddLogMessage($"File [{oResponse.FileName}] loaded: [{FormatTime(oSWTotal.ElapsedMilliseconds)}]")
        Catch ex As FaultException
            MsgBox(ex.Reason.ToString, MsgBoxStyle.Critical, "Error from Service")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Uh oh!")
        End Try
    End Sub

    Private Async Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Try
            Dim oSWTotal As New Stopwatch()
            oSWTotal.Start()

            Dim oObjectId As Integer = TextboxObejctId.EditValue

            Dim oResponse = Await _Channel.GetFileByObjectIdAsync(New EDMIServiceReference.DocumentStreamRequest() With {.ObjectId = oObjectId})
            Dim oMemoryStream As New MemoryStream()
            oResponse.FileContents.CopyTo(oMemoryStream)
            oMemoryStream.Position = 0

            DocumentViewer1.LoadFile(oResponse.FileName, oMemoryStream)

            oSWTotal.Stop()
            AddLogMessage($"File [{oResponse.FileName}] loaded: [{FormatTime(oSWTotal.ElapsedMilliseconds)}]")
        Catch ex As Exception
            AddLogMessage($"Error while getting file: [{ex.Message}]")
        End Try
    End Sub

    Private Sub BarToggleSwitchItem1_CheckedChanged(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarToggleSwitchItem1.CheckedChanged
        If BarToggleSwitchItem1.Checked Then
            If TextboxObejctId.EditValue = "" Then
                Timer1.Stop()
                MsgBox("Please set a ObjectId!", MsgBoxStyle.Critical, Text)
            Else
                Timer1.Start()
                AddLogMessage("Timer Started!")
            End If
        Else
            Timer1.Stop()
            AddLogMessage("Timer Stopped!")
        End If
    End Sub
End Class
