Imports System.ServiceModel
Imports System.ServiceProcess
Imports System.Configuration
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Database.Exceptions

Public Class WindowsService
    Inherits ServiceBase

    Private _serviceHost As ServiceHost = Nothing

    Private _logConfig As LogConfig
    Private _logger As Logger
    Private _db As Firebird
    Private _clientsConnected As Integer = 0
    Private _clients As New List(Of Session)

    Public Sub New()
        ServiceName = SERVICE_NAME
    End Sub

    Public Shared Sub Main()
        Run(New WindowsService())
    End Sub

    Protected Overrides Sub OnStart(ByVal args As String())
        Try
            _logConfig = New LogConfig(LogConfig.PathType.CustomPath, AppConfig.ConfigPath)
            _logger = _logConfig.GetLogger()

            _logger.Info("Service {0} is starting", SERVICE_DISPLAY_NAME)

            AddHandler LicenseService.ClientConnectedEvent, AddressOf EDMService_ClientConnected
            AddHandler LicenseService.ClientDisconnectedEvent, AddressOf EDMService_ClientDisonnected

            LicenseService.LogConfig = _logConfig

            _logger.Info("Starting the WCF Service")

            _serviceHost = New ServiceHost(GetType(LicenseService))
            _serviceHost.Open()

            _logger.Info("Successfully started the WCF Service!")

            _logger.Info("Service {0} successfully started!", SERVICE_DISPLAY_NAME)
        Catch ex As Exception
            _logger.Error(ex, "Failed to start the service host!")
        End Try
    End Sub

    Private Sub EDMService_ClientDisonnected(sender As Object, e As Session)
        _clientsConnected -= 1
        _clients.Remove(e)
        _logger.Info("Client {0}/{1} disconnected! Total {2}", e.Username, e.SessionId, _clientsConnected)
    End Sub

    Private Sub EDMService_ClientConnected(sender As Object, e As Session)
        _clientsConnected += 1
        _clients.Add(e)
        _logger.Info("Client {0}/{1} connected! Total {2}", e.Username, e.SessionId, _clientsConnected)
    End Sub

    Protected Overrides Sub OnStop()
        If _serviceHost IsNot Nothing Then
            _serviceHost.Close()
            _serviceHost = Nothing
        End If
        _logger.Info("Service {0} is stopping!", SERVICE_DISPLAY_NAME)
    End Sub
End Class

