Imports GPSConnector.Common
Imports System.Collections.Concurrent

Public Class GPSConnectorServiceSetting
    Private ReadOnly _components As List(Of GPSDeviceTypeComponent)
    Private WithEvents _logger As IGPSLogger
    Private ReadOnly _customServices As List(Of ICustomService)
    Private ReadOnly _database As IDatabase
    Private ReadOnly _latestGPSDeviceData As ConcurrentDictionary(Of String, GPSDeviceData) = New ConcurrentDictionary(Of String, GPSDeviceData)()
    Private _vitalMessageEmails As String
    Private ReadOnly _mailList As List(Of String) = New List(Of String)()

    Public Sub New(ByVal components As List(Of GPSDeviceTypeComponent), ByVal logger As IGPSLogger, ByVal database As IDatabase, ByVal customServices As List(Of ICustomService))
        _logger = logger
        _components = components
        _database = database
        _customServices = customServices

        For Each component In _components
            AddHandler component.GPSDataArrival, AddressOf ComponentGPSDataArrival
        Next
    End Sub
    Public Property VitalMessageEmails() As String
        Get
            Return _vitalMessageEmails
        End Get
        Set(value As String)
            _vitalMessageEmails = value
            _mailList.Clear()

            Dim m = _vitalMessageEmails.Split(",")
            If Not m Is Nothing AndAlso m.Count > 0 Then
                For Each s As String In m
                    If Not String.IsNullOrEmpty(s.Trim()) Then _mailList.Add(s)
                Next
            End If
        End Set
    End Property
    Public Function LatestGPSDeviceData() As List(Of GPSDeviceData)
        Return _latestGPSDeviceData.Values.ToList()
    End Function
    Public ReadOnly Property Components As List(Of GPSDeviceTypeComponent)
        Get
            Return _components
        End Get
    End Property

    Public ReadOnly Property Logger As IGPSLogger
        Get
            Return _logger
        End Get
    End Property
    Public ReadOnly Property Database As IDatabase
        Get
            Return _database
        End Get
    End Property

    Public ReadOnly Property CustomServices As List(Of ICustomService)
        Get
            Return _customServices
        End Get
    End Property

    Private Sub LoggerNewImmediateLogInfo(e As ImmediateLogInforEventArg, sender As Object) Handles _logger.NewImmediateLogInfo
        Try
            If Subscribers.Count > 0 Then
                For i As Integer = Subscribers.Count - 1 To 0 Step -1
                    Dim subscriber = Subscribers(i)
                    Try
                        Dim owner As Owner = _database.GetOwner(subscriber.OwnerKey)

                        If owner Is Nothing OrElse Not owner.IsAdmin Then
                            Continue For
                        End If

                        Dim communicationObject = CType(subscriber.GPSConnectorStatusServiceCallBack, ICommunicationObject)
                        If communicationObject.State = CommunicationState.Opened Then
                            subscriber.GPSConnectorStatusServiceCallBack.NewLogInfo(e.LogInfo)
                        Else
                            Subscribers.Remove(subscriber)
                        End If
                    Catch ex As Exception

                    End Try

                Next
            End If
            'If e.Vital Then
            '    SendMail(e.LogInfo)
            'End If
        Catch ex As Exception
            _logger.LogException(ex, "ComponentGPSDataArrival", False)
        End Try
    End Sub

    Private Sub ComponentGPSDataArrival(e As GPSDeviceTypeComponentEventArg, sender As Object)
        Try
            If _latestGPSDeviceData.ContainsKey(e.GPSDeviceData.Id) Then
                _latestGPSDeviceData(e.GPSDeviceData.Id) = e.GPSDeviceData
            Else
                _latestGPSDeviceData.AddOrUpdate(e.GPSDeviceData.Id, e.GPSDeviceData, Function(k, v) v)
            End If

            If Subscribers.Count > 0 Then
                For i As Integer = Subscribers.Count - 1 To 0 Step -1
                    Dim subscriber = Subscribers(i)
                    Try
                        Dim owner As Owner = _database.GetOwner(subscriber.OwnerKey)
                        If owner Is Nothing Then
                            Subscribers.Remove(subscriber)
                            Continue For
                        ElseIf Not owner.IsAdmin AndAlso Not _database.IsDeviceOwnedBy(e.GPSDeviceData.Id, owner.ID) Then
                            Continue For
                        End If
                        Dim communicationObject = CType(subscriber.GPSConnectorStatusServiceCallBack, ICommunicationObject)
                        If communicationObject.State = CommunicationState.Opened Then
                            subscriber.GPSConnectorStatusServiceCallBack.NewDeviceData(e.GPSDeviceData)
                        Else
                            Subscribers.Remove(subscriber)
                        End If
                    Catch ex As Exception

                    End Try

                Next
            End If
        Catch ex As Exception
            _logger.LogException(ex, "ComponentGPSDataArrival", False)
        End Try

    End Sub

    '    Private Sub SendMail(logInfo As LogInfo)
    '        Try
    '            If _mailList.Count = 0 Then Exit Sub
    '
    '            Dim message As MailMessage = New MailMessage()
    '
    '            With message
    '
    '                For Each s As String In _mailList
    '                    .To.Add(New MailAddress(s))
    '                Next
    '                .Subject = "GPSConnector Vital Message"
    '                .Body = "Hello Admin," + vbCrLf
    '                .Body += "Vital Message from GPSConnector. Please, check your service as soon as possible" + vbCrLf
    '                .Body += "Log Date  : " + logInfo.LogDate.ToString() + vbCrLf
    '                .Body += "Log Type  : " + logInfo.LogType.ToString() + vbCrLf
    '                .Body += "Log Owner : " + logInfo.Owner + vbCrLf
    '                .Body += "Log Message : " + logInfo.Log + vbCrLf
    '                .Body += "Thank you"
    '            End With
    '
    '            Dim client = New SmtpClient()
    '            client.Send(message)
    '        Catch ex As Exception
    '            _logger.LogException(ex, "GPSConnectorServiceSetting")
    '        End Try
    '    End Sub

End Class
