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
    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
    Private _Global As GlobalState

    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
            _Config = New AppConfig()
            _LogConfig = New LogConfig(LogConfig.PathType.CustomPath, "E:\EDMService") With {
                .Debug = True
            }
            _Logger = _LogConfig.GetLogger()
            _Logger.Info("Service {0} is starting...", SERVICE_DISPLAY_NAME)

            MaybeStartFirebird()
            MaybeStartMSSQL()

            _Logger.Debug("Initializing EDMI Functions")

            _Archive = New EDMI.File.Archive(_LogConfig)
            _Filesystem = New Filesystem.File(_LogConfig)
            _Global = New GlobalState(_LogConfig, _MSSQL)

            _Global.LoadObjectStores()

            _Logger.Info("EDMI Functions initialized.")

            EDMIService.MSSQL = _MSSQL
            EDMIService.Firebird = _Firebird
            EDMIService.LogConfig = _LogConfig
            EDMIService.AppConfig = _Config
            EDMIService.EDMIArchive = _Archive
            EDMIService.Filesystem = _Filesystem
            EDMIService.GlobalState = _Global

            _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

    Private Sub MaybeStartFirebird()
        If _Config.IsFirebirdConfigured() Then
            _Logger.Debug("Connecting to Firebird")
            _Firebird = New Firebird(
                _LogConfig,
                _Config.FirebirdDataSource,
                _Config.FirebirdDatabase,
                _Config.FirebirdUser,
                _Config.FirebirdPassword
            )
            _Logger.Info("Database connection established.")
        Else
            _Logger.Info("Firebird is not configured, will not be used!")
        End If
    End Sub

    Private Sub MaybeStartMSSQL()
        If _Config.IsMSSQLConfigured() Then
            _Logger.Debug("Connecting to MSSQL")
            _MSSQL = New MSSQLServer(_LogConfig, _Config.MSSQLConnectionString)
            _Logger.Info("Database connection established.")
        Else
            _Logger.Info("MSSQL is not configured, will not be used!")
        End If
    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

