Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
Imports DigitalData.Modules.Logging

Public Class LicenseFile
    Public Const LICENSE_FILENAME = "License.xml"

    Public ReadOnly Path As String
    Private _Logger As Logger

    Public Sub New(LogConfig As LogConfig, Path As String)
        Me.Path = Path
        _Logger = LogConfig.GetLogger()
    End Sub

    Private Function GetSerializer() As XmlSerializer
        Dim oSerializer As New XmlSerializer(GetType(LicenseSchema))
        Return oSerializer
    End Function

    Public Function TestFileValid(Optional FileName As String = LICENSE_FILENAME) As Boolean
        Try
            Dim oSerializer = GetSerializer()
            Dim oFilePath As String = IO.Path.Combine(Path, FileName)

            Using oReader As New StreamReader(oFilePath),
                oXmlReader = XmlReader.Create(oReader)
                Return oSerializer.CanDeserialize(oXmlReader)
            End Using
        Catch ex As Exception
            _Logger.Error(ex)
            Throw ex
        End Try
    End Function

    Public Function LoadFile(Optional FileName As String = LICENSE_FILENAME) As LicenseSchema
        Try
            Dim oSerializer = GetSerializer()
            Dim oFilePath As String = IO.Path.Combine(Path, FileName)
            Dim oLicense As LicenseSchema

            Using oReader As New StreamReader(oFilePath)
                oLicense = oSerializer.Deserialize(oReader)
            End Using

            Return oLicense
        Catch ex As Exception
            _Logger.Error(ex)
            Throw ex
        End Try
    End Function

    Public Function Serialize(License As LicenseSchema) As Byte()
        Try
            Dim oSerializer = GetSerializer()

            Using oStream = New MemoryStream()
                oSerializer.Serialize(oStream, License)
                Return oStream.ToArray()
            End Using
        Catch ex As Exception
            _Logger.Error(ex)
            Throw ex
        End Try
    End Function

    Public Sub SaveFile(License As LicenseSchema, Optional FileName As String = LICENSE_FILENAME)
        Try
            Dim oBytes = Serialize(License)
            Dim oFilePath As String = IO.Path.Combine(Path, FileName)

            Using oFileStream = New FileStream(oFilePath, FileMode.Create, FileAccess.Write)
                oFileStream.Write(oBytes, 0, oBytes.Length)
            End Using
        Catch ex As Exception
            _Logger.Error(ex)
            Throw ex
        End Try
    End Sub
End Class
