Imports System.Timers
Imports DigitalData.GUIs.ClientSuite.Base
Imports DigitalData.Modules.Logging

Namespace Workers
    Public Class HeartbeatWorker
        Inherits BaseClass
        Implements IWorker

        Public Event OnlineChanged As OnlineChangedEventHandler
        Public Delegate Sub OnlineChangedEventHandler(sender As Object, Online As Boolean)

        Public ReadOnly Property Interval As Integer = 4000 Implements IWorker.Interval
        Public ReadOnly Property Name As String = "Heartbeat Worker" Implements IWorker.Name

        Public Sub New(LogConfig As LogConfig)
            MyBase.New(LogConfig)
        End Sub

        Public Sub Setup() Implements IWorker.Setup
            Logger.Debug("Starting {0}", "HeartbeatWorker")
        End Sub

        Public Async Sub Callback(Manager As WorkerManager, e As ElapsedEventArgs) Implements IWorker.Callback
            Try
                If My.Channel.State = ServiceModel.CommunicationState.Faulted Then
                    My.Channel = My.ChannelFactory.CreateChannel()
                End If

                ' Connect to service and send hearbeat request
                Dim oResult = Await My.Channel.HeartbeatAsync()

                Logger.Debug("Service is online")

                SetOnlineState(True)
            Catch ex As Exception

                Logger.Debug("Service is offline!")
                Logger.Error(ex)

                Manager.StopWorkers()
                SetOnlineState(False)
            Finally
                My.Application.Service.LastChecked = DateTime.Now
            End Try
        End Sub

        Public Sub Teardown() Implements IWorker.Teardown
            Logger.Debug("Stopping {0}", Name)
        End Sub

        Private Sub SetOnlineState(NewState As Boolean)
            If My.Application.Service.Online <> NewState Then
                My.Application.Service.Online = NewState
                RaiseEvent OnlineChanged(Me, NewState)
            End If
        End Sub
    End Class
End Namespace

