Imports GPSConnector.Common
Imports log4net

Public Class GPSLogger
    Implements IGPSLogger
    Private Shared ReadOnly Log As ILog = LogManager.GetLogger(GetType(GPSLogger))
    Private ReadOnly _immediateReportErrors As Queue(Of LogInfo) = New Queue(Of LogInfo)
    Private ReadOnly _immediateReportInformation As Queue(Of LogInfo) = New Queue(Of LogInfo)
    Private Const MaximalSize As Integer = 50
    Private ReadOnly _maxSize As Integer
    Public Sub New(Optional immediateReportSize As Integer = MaximalSize)
        _maxSize = immediateReportSize
    End Sub

    Public Sub LogException(exception As Exception, owner As String, Optional immediateReport As Boolean = False, Optional vital As Boolean = False) Implements IGPSLogger.LogException
        Dim msg As String
        msg = String.Format("An error is thrown by '{0}'", owner)
        Log.Error(msg, exception)
        If immediateReport Then
            If _immediateReportErrors.Count > _maxSize Then
                _immediateReportErrors.Dequeue()
            End If
            Dim logInfo As LogInfo = New LogInfo() With {.Log = exception.Message, .LogDate = DateTime.Now, .LogType = EnLogInfoType.[Error], .Owner = owner}
            _immediateReportErrors.Enqueue(logInfo)
            RaiseEvent NewImmediateLogInfo(New ImmediateLogInforEventArg(logInfo, vital), Me)
        End If
    End Sub

    Public Sub LogDebugInfo(ByVal msg As String, ByVal owner As String) Implements IGPSLogger.LogDebugInfo
        Log.DebugFormat("Owner : {0}, Message {1}", owner, msg)
    End Sub

    Public Function GetImmediateLogInfo(ByVal logInfoType As EnLogInfoType) As List(Of LogInfo) Implements IGPSLogger.GetImmediateLogInfo

        Select Case logInfoType
            Case EnLogInfoType.[Error]
                Return _immediateReportErrors.ToList
            Case Else
                Return _immediateReportInformation.ToList
        End Select
    End Function

    Public Event NewImmediateLogInfo(ByVal e As ImmediateLogInforEventArg, ByVal sender As Object) Implements IGPSLogger.NewImmediateLogInfo

    Public Sub LogInformation(msg As String, owner As String, Optional immediateReport As Boolean = False, Optional vital As Boolean = False) Implements IGPSLogger.LogInformation
        Log.InfoFormat("Onwer : {0}, Message {1}", owner, msg)
        If immediateReport = True Then
            If _immediateReportInformation.Count > _maxSize Then
                _immediateReportInformation.Dequeue()
            End If
            Dim logInfo As LogInfo = New LogInfo() With {.Log = msg, .LogDate = DateTime.Now, .LogType = EnLogInfoType.Information, .Owner = owner}
            _immediateReportInformation.Enqueue(logInfo)
            RaiseEvent NewImmediateLogInfo(New ImmediateLogInforEventArg(logInfo, vital), Me)
        End If
    End Sub


End Class
