Imports System.IO
Imports DigitalData.Modules.Config
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Logging.LogConfig

Public Class ZUGFeRDService
    Private _config As ConfigManager(Of Config)
    Private _logConfig As LogConfig
    Private _logger As Logger
    Private _firebird As Firebird
    Private _mssql As MSSQLServer = Nothing

    Private _threadRunner As ThreadRunner

    Protected Overrides Sub OnStart(args() As String)
        _logConfig = New LogConfig(PathType.CustomPath, Path.Combine(My.Application.Info.DirectoryPath, "Log"), Nothing, "Digital Data", "DDZUGFeRDService")
        _config = New ConfigManager(Of Config)(_logConfig, My.Application.Info.DirectoryPath)
        _logConfig.Debug = _config.Config.Debug
        _logger = _logConfig.GetLogger()
        Try
            Dim directory As New IO.DirectoryInfo(_logConfig.LogDirectory)

            For Each file As IO.FileInfo In directory.GetFiles
                If (Now - file.CreationTime).Days > 29 Then
                    file.Delete()
                Else
                    Exit For
                End If
            Next
        Catch ex As Exception

        End Try
        _logger.Info($"{Constants.SERVICE_NAME} is starting.")

        Dim oDataSource As String = _config.Config.Firebird.DataSource
        Dim oDatabase As String = _config.Config.Firebird.Database
        Dim oUser As String = _config.Config.Firebird.User
        Dim oPassword As String = _config.Config.Firebird.Password
        Dim oJobInterval As Integer = _config.Config.JobInterval
        Dim oMSSQLConnectionString As String = _config.Config.MSSQLConnectionString
        Dim oMSSQLEnabled As Boolean = _config.Config.MSSQLEnabled

        _firebird = New Firebird(_logConfig, oDataSource, oDatabase, oUser, oPassword)

        If oMSSQLEnabled = True Then
            _mssql = New MSSQLServer(_logConfig, oMSSQLConnectionString)

            If _mssql.DBInitialized = False Then
                _logger.Warn("MSSQL Connection could not be initialized. Disabling MSSQL.")
                _mssql = Nothing
            End If
        End If

        Try
            _threadRunner = New ThreadRunner(_logConfig, _config, _firebird, _mssql)
            _threadRunner.Start(oJobInterval)
        Catch ex As Exception
            _logger.Error(ex)
        End Try
    End Sub

    Protected Overrides Sub OnStop()
        _logger.Info($"{Constants.SERVICE_NAME} is stopping.")

        _threadRunner.Stop()
    End Sub

End Class
