Imports System.ComponentModel
Imports System.IO
Imports EmailProfiler.Common
Imports DigitalData.Modules.Config
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Logging

Public Class MyService
#Region "+++++ variables +++++"
    Private Worker As BackgroundWorker
    Private WithEvents Timer As New Timers.Timer

    Private LogConfig As LogConfig
    Private Logger As Logger

    'Private EmailWorker As clsWorkEmail

    Private _DBConfig As ClassDBConfig.Config

    Private ConfigManager As ConfigManager(Of Config)
    Private _ConfigData As Config

    Private Database As MSSQLServer
#End Region

    Protected Overrides Sub OnStart(args() As String)
        Try
            Dim oLogPath = Path.Combine(My.Application.Info.DirectoryPath, "Log")
            LogConfig = New LogConfig(LogConfig.PathType.CustomPath, oLogPath, Nothing, "Digital Data", "DD EmailProfiler", 30)
            Logger = LogConfig.GetLogger

            Logger.Info("Service started.")

            ConfigManager = New ConfigManager(Of Config)(LogConfig, My.Application.Info.DirectoryPath)
            _ConfigData = ConfigManager.Config

            If _ConfigData.ConnectionString = String.Empty Then
                Logger.Warn("No ConnectionString configured. Exiting.")
            Else
                If _ConfigData.Debug = True Then
                    LogConfig.Debug = True
                Else
                    LogConfig.Debug = False
                End If

                Database = New MSSQLServer(LogConfig, _ConfigData.ConnectionString)
                Logger.Debug("Database initialized!")

                Dim oDBConfigManager As ClassDBConfig = New ClassDBConfig(LogConfig, Database)
                _DBConfig = oDBConfigManager.GetConfig()

                If _DBConfig IsNot Nothing Then
                    Logger.Debug("DBConfig initialized!")
                Else
                    Logger.Warn("Error while initializing DBConfig")
                End If

                ' MP 10.01.25 - Das Objekt wird hier gar nicht weiter verwendet. erstmal raus damit
                'EmailWorker = New clsWorkEmail(LogConfig, _ConfigData.ConnectionString, _DBConfig.WindreamConnectionString, _ConfigData)
                'Logger.Debug("Module Workmail initialized")

                If Database.DBInitialized = False Then
                    Logger.Warn("No Connection was established! Exiting.")
                Else
                    '### Thread für das nachträgliche Setzen von Rechten generieren
                    Logger.Debug("Setting up Background Worker")
                    Worker = New BackgroundWorker With {
                        .WorkerReportsProgress = True,
                        .WorkerSupportsCancellation = True
                    }
                    AddHandler Worker.DoWork, AddressOf DoWork
                    AddHandler Worker.RunWorkerCompleted, AddressOf Worker_Completed

                    ' Set the Interval
                    Timer.Interval = _DBConfig.TimerInterval * 60000
                    Timer.Enabled = True
                    Logger.Debug("Timer started.")

                    ' Und den Durchlauf das erste Mal starten
                    Worker.RunWorkerAsync()
                End If
            End If
        Catch ex As Exception
            Logger.Warn("Unexpected error while starting.")
            Logger.Error(ex)
        End Try
    End Sub
    Public Sub Thread_Run() Handles Timer.Elapsed
        Logger.Debug("Starting Worker..")
        If Not Worker.IsBusy Then
            Logger.Debug("Running Worker..")
            Worker.RunWorkerAsync()
        End If
    End Sub
    Public Sub DoWork(sender As Object, e As DoWorkEventArgs)
        Try
            Dim oProfileIdForPolling = 0

            Dim oWorker As New clsWorker(LogConfig,
                                         _ConfigData.ConnectionString,
                                         _DBConfig.WindreamConnectionString,
                                         oProfileIdForPolling,
                                         _ConfigData)
            oWorker.Start_WorkingProfiles(False)
        Catch ex As Exception
            Logger.Error(ex)
        End Try
    End Sub
    Protected Overrides Sub OnStop()
        Logger.Info("## Service was stopped manually. ##")
    End Sub

    Private Sub Worker_Completed(sender As Object, e As RunWorkerCompletedEventArgs)
        'This event fires when the DoWork event completes
        Try
            Dim result As String = ""
            If e.Cancelled Then
                EventLog.WriteEntry("DD EmailProfiler", "The thread was cancelled!", EventLogEntryType.Error)
                Logger.Warn("## The thread was cancelled.")
            ElseIf e.Error IsNot Nothing Then
                EventLog.WriteEntry("DD EmailProfiler", "Unexpected error in thread!", EventLogEntryType.Error)
                Logger.Warn("Unexpected error in thread: " & e.Error.Message)
            End If
        Catch ex As Exception
            Logger.Error(ex)
        End Try
    End Sub
End Class
