Imports System.IO
Imports System.IO.Compression
Imports DigitalData.Modules.Logging

Public Class Compression
    Private ReadOnly _logger As Logger

    Public Sub New(LogConfig As LogConfig)
        _logger = LogConfig.GetLogger()
    End Sub

    Public Async Function CompressAsync(data As Byte()) As Task(Of Byte())
        Return Await Task.Run(Function() As Byte()
                                  Return Compress(data)
                              End Function)
    End Function

    Public Function Compress(data As Byte()) As Byte()
        Try
            ' ByteArray in Stream umwandeln
            Using originalStream As New MemoryStream(data)
                ' Ziel Stream erstellen
                Using compressedStream As New MemoryStream()
                    ' Gzip-Stream erstellen, der alle Daten komprimiert und zu compressedStream durchleitet
                    '
                    '  > MemoryStream      > GzipStream          > MemoryStream  
                    '  originalStream  --> compressionStream --> compressedFileStream
                    '
                    Using compressionStream As New GZipStream(compressedStream, CompressionMode.Compress)
                        originalStream.CopyTo(compressionStream)
                        compressionStream.Close()
                        Return compressedStream.ToArray()
                    End Using
                End Using
            End Using
        Catch ex As Exception
            _logger.Error(ex)
            Throw ex
        End Try
    End Function

    Public Async Function DecompressAsync(data As Byte()) As Task(Of Byte())
        Return Await Task.Run(Function() As Byte()
                                  Return Decompress(data)
                              End Function)
    End Function

    Public Function Decompress(data As Byte()) As Byte()
        Try
            ' ByteArray in Stream umwandeln
            Using compressedStream As New MemoryStream(data)
                ' Ziel Stream erstellen
                Using decompressedStream As New MemoryStream()
                    ' Gzip-Stream erstellen, der alle Daten komprimiert und zu compressedStream durchleitet
                    '
                    '  > MemoryStream        > GzipStream            > MemoryStream  
                    '  compressedStream  --> decompressionStream --> decompressedStream
                    '
                    Using decompressionStream As New GZipStream(compressedStream, CompressionMode.Decompress)
                        decompressionStream.CopyTo(decompressedStream)
                        Return decompressedStream.ToArray()
                    End Using
                End Using
            End Using
        Catch ex As Exception
            _logger.Error(ex)
            Throw ex
        End Try
    End Function
End Class
