Imports System.ServiceModel
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.EDMI.API
Imports System.IO
Imports DigitalData.Modules.EDMI.API.EDMIServiceReference

Public Class Form1
    Private _LogConfig As LogConfig
    Private _Logger As Logger
    Private _Client As Client

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            _LogConfig = New LogConfig(LogConfig.PathType.Temp, Nothing, "EDMIBenchmark")
            _Logger = _LogConfig.GetLogger()
            _Client = New Client(_LogConfig, "172.24.12.39", 9000)
            _Client.Connect()

            DocumentViewer1.Init(_LogConfig, "21182889975216572111813147150675976632")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, Text)
        End Try
    End Sub

    Private Sub AddLogMessage(Message As String)
        _Logger.Info(Message)
        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()
        listboxFiles.Items.Clear()

        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
        Try
            Dim oFiles As New List(Of String)
            Dim oSWTotal As New Stopwatch()
            oSWTotal.Start()
            Dim oCountFiles As Integer = 0
            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 oObjectId As Long = Await _Client.NewFileAsync(oFileInfo.FullName, "Work", "DOC", "DEFAULT")
                AddLogMessage($"File with Id [{oObjectId}] imported!")
                oCountFiles += 1
                oSW.Stop()
                AddLogMessage($"Import Time: {FormatTime(oSW.ElapsedMilliseconds)}")
                AddLogMessage("")
            Next

            oSWTotal.Stop()
            AddLogMessage($"Imported {oCountFiles} files - Total Time: {FormatTime(oSWTotal.ElapsedMilliseconds)}")
            MsgBox($"Imported {oCountFiles} files - Total Time: {FormatTime(oSWTotal.ElapsedMilliseconds)}", MsgBoxStyle.Information)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, Text)
        End Try
    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 Sub ButtonLoadFile_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles ButtonLoadFile.ItemClick
        Try
            Dim oSWTotal As New Stopwatch()
            oSWTotal.Start()

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

            Dim oObjectId As Integer = TextboxObjectId.EditValue
            Dim oResponse As Client.DocumentInfo = _Client.GetDocumentInfo(2, oObjectId)

            DocumentViewer1.LoadFile(oResponse.FullPath)

            oSWTotal.Stop()
            AddLogMessage($"File [{oResponse.FullPath}] 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 As Client.FileList = Await _Client.ListFilesForUserAsync()
    '        Dim oParams As New DocumentResultParams() With {
    '            .Results = New List(Of DocumentResult) From {
    '                New DocumentResult() With {.Title = "lol", .Datatable = oResult.Datatable}
    '            },
    '            .WindowGuid = "1",
    '            .ColumnNames = New ColumnNames() With {
    '                .FilenameColumn = "FILENAME_EXT",
    '                .FullPathColumn = "FULL_PATH",
    '                .ObjectIdColumn = "IDB_OBJ_ID"
    '            }
    '        }
    '        Dim oEnv As New DigitalData.Modules.ZooFlow.Environment() With {
    '            .Service = New ServiceState() With {
    '                .IsActive = True,
    '                .Address = "172.24.12.39:9000"
    '            },
    '            .Settings = New SettingsState With {
    '                .GdPictureKey = "21182889975216572111813147150675976632"
    '            },
    '            .User = New UserState(2)
    '        }
    '        Dim oForm As New frmDocumentResultList(_LogConfig, oEnv, oParams)
    '        oForm.Show()
    '    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 Long = oRow.Item("IDB_OBJ_ID")
    '        Dim oResponse As Client.StreamedFile = Await _Client.GetFileByObjectIdAsync(oObjectId)

    '        DocumentViewer1.LoadFile(oResponse.FileName, oResponse.Stream)

    '        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 = TextboxObjectId.EditValue

    '        Dim oResponse As Client.StreamedFile = Await _Client.GetFileByObjectIdAsync(oObjectId)

    '        DocumentViewer1.LoadFile(oResponse.FileName, oResponse.Stream)

    '        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 TextboxObjectId.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

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
        Process.Start(_LogConfig.LogDirectory)
    End Sub

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

            If TextboxDatatableName.EditValue = "" Then
                MsgBox("Please enter a Datatable name!", MsgBoxStyle.Exclamation, "Uh oh!")
            End If

            Dim oDatatableName As String = TextboxDatatableName.EditValue
            Dim oSortExpression As String = TextboxDatatableSort.EditValue
            Dim oFilterExpression As String = TextboxDatatableFilter.EditValue
            Dim oResponse As TableResult = Await _Client.GetDatatableByNameAsync(oDatatableName, oFilterExpression, oSortExpression)
            Dim oDt As DataTable = oResponse.Table
            GridControl1.DataSource = oDt
            oSWTotal.Stop()

            If oResponse.OK Then
                AddLogMessage(Now.ToLongTimeString + $"DataTable [{oDatatableName}] loaded: [{FormatTime(oSWTotal.ElapsedMilliseconds)}]")
            Else
                AddLogMessage(Now.ToLongTimeString + $"DataTable [{oDatatableName}] could not be loaded. Error: {oResponse.ErrorMessage}")
            End If
        Catch ex As FaultException
            MsgBox(ex.Reason.ToString, MsgBoxStyle.Critical, "Error from Service")
            _Client.Reconnect()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Uh oh!")
            _Client.Reconnect()
        End Try
    End Sub
End Class
