Imports System.ServiceModel
Imports System.ServiceProcess
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Database
Imports DigitalData.Modules
Imports System.ServiceModel.Description

Public Class WindowsService
    Inherits ServiceBase

    Private _serviceHost As ServiceHost = Nothing
    Private _edmService As IEDMIService = Nothing

    Private _logConfig As LogConfig
    Private _logger As Logger

    Private _firebird As Firebird
    Private _mssql As MSSQLServer

    Private _config As AppConfig
    Private _Path As EDMI.File.Path
    Private _Archive As EDMI.File.Archive
    Private _filesystem As Filesystem.File

    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
            AppConfig.Load()

            _logConfig = New LogConfig(LogConfig.PathType.CustomPath, "E:\EDMService") With {
                .Debug = True
            }

            _logger = _logConfig.GetLogger()

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

            If AppConfig.IsFirebirdConfigured() Then
                _logger.Debug("Connecting to Firebird...")
                _firebird = New Firebird(
                    _logConfig,
                    AppConfig.FirebirdDataSource,
                    AppConfig.FirebirdDatabase,
                    AppConfig.FirebirdUser,
                    AppConfig.FirebirdPassword
                )
                _logger.Info("Database connection established.")
            Else
                _logger.Info("Firebird is not configured, will not be used!")
            End If

            If AppConfig.IsMSSQLConfigured() Then
                _logger.Debug("Connecting to MSSQL...")
                _mssql = New MSSQLServer(_logConfig, AppConfig.MSSQLConnectionString)
                _logger.Info("Database connection established.")
            Else
                _logger.Info("MSSQL is not configured, will not be used!")
            End If

            _logger.Debug("Initializing EDMI Functions")

            _Path = New EDMI.File.Path(_logConfig, AppConfig.DatastorePath)
            _Archive = New EDMI.File.Archive(_logConfig)
            _filesystem = New Filesystem.File(_logConfig)

            _logger.Info("EDMI Functions initialized.")

            EDMIService.MSSQL = _mssql
            EDMIService.Firebird = _firebird
            EDMIService.LogConfig = _logConfig
            EDMIService.AppConfig = _config
            EDMIService.EDMIArchive = _Archive
            EDMIService.EDMIPath = _Path
            EDMIService.Filesystem = _filesystem

            _logger.Debug("Starting WCF ServiceHost...")

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

            _logger.Info("WCF ServiceHost started.")

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

    Protected Overrides Sub OnStop()
        GracefullyStop()
    End Sub

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

