'Imports System.Collections.ObjectModel
Imports System.ComponentModel
Imports System.IO
Imports DD_WMResulthandler
Imports DigitalData.Modules.Logging
Public Class DDWDResultHandler
#Region "+++++ Variablen +++++"
    Private _windream As DD_WMResulthandler.clsWindream_allgemein
    Private _database As DD_WMResulthandler.clsDatabase
    Private _profil As clsProfil

    Public Shared threadResultHandler As BackgroundWorker
    Public Shared threadPMRefresh As BackgroundWorker

    Private Logger As Logger
    Private MyLogger As LogConfig

    'Private LoggerPMR As Logger
    'Private MyLoggerPMR As LogConfig
    Private PMRefresh As clsPMRefresh

    Public Shared _PROFIL_ID As Integer
    Dim _INTERVALL As Integer
    Dim oFirstRun As Boolean = False
    'Variablen für Dateiimporter

#End Region
    Public Sub New()
        MyBase.New()
        InitializeComponent()
    End Sub
    Protected Overrides Sub OnStart(ByVal args() As String)
        ' Code zum Starten des Dienstes hier einfügen. Diese Methode sollte Vorgänge
        ' ausführen, damit der Dienst gestartet werden kann.
        'EventLog1.WriteEntry("Dienst 'DD windream Result Handler' gestartet")
        Try
            Try
                MyLogger = New LogConfig(LogConfig.PathType.CustomPath, Path.Combine(My.Application.Info.DirectoryPath, "Log"))
                Logger = MyLogger.GetLogger()
                _database = New clsDatabase(MyLogger)

            Catch ex As Exception
                EventLog.WriteEntry("DDWMResultHandler", "ERROR in CREATING-LOG:" & ex.ToString(), EventLogEntryType.Error)
            End Try


            'If _database.Init(My.Settings.SQLSERVER_CS_RH, True) = False Then
            '        Logger.Warn("Achtung: Es konnte keine Verbindung zur Datenbank '" & My.Settings.SQLSERVER_CS_RH & "' hergestellt werden!")
            '    Else


            MyLogger.Debug = clsCURRENT.DEBUG


            oFirstRun = True
            '        '#Thread für Durchlauf generieren
            DDWDResultHandler.threadResultHandler = New BackgroundWorker()
            DDWDResultHandler.threadResultHandler.WorkerReportsProgress = True
            DDWDResultHandler.threadResultHandler.WorkerSupportsCancellation = True
            AddHandler threadResultHandler.DoWork, AddressOf RUN_RESULTHANDLER
            AddHandler threadResultHandler.RunWorkerCompleted, AddressOf Thread_Completed

            '        '### Den Timer generieren
            Dim Timer_Durchlauf As New System.Timers.Timer()
            'Das Event hinterlegen welches bei "Tick" ausgelöst wird
            AddHandler Timer_Durchlauf.Elapsed, AddressOf Thread_Run
            ' Set the Interval
            Timer_Durchlauf.Interval = 60000
            Timer_Durchlauf.Enabled = True
            Logger.Debug("Timer Resulthandler gestartet")
            ' Und den Durchlauf das erste Mal starten



            DDWDResultHandler.threadPMRefresh = New BackgroundWorker()
            DDWDResultHandler.threadPMRefresh.WorkerReportsProgress = True
            DDWDResultHandler.threadPMRefresh.WorkerSupportsCancellation = True
            AddHandler threadPMRefresh.DoWork, AddressOf RUNPMRefresh
            AddHandler threadPMRefresh.RunWorkerCompleted, AddressOf ThreadPMRefresh_Completed

            '        '### Den Timer generieren
            Dim TimerPMRefresh As New System.Timers.Timer()
            'Das Event hinterlegen welches bei "Tick" ausgelöst wird
            AddHandler TimerPMRefresh.Elapsed, AddressOf ThreadPMRefreshRun

            ' Set the Interval
            Dim oIntervallMS = (My.Settings.PMREFRESH_INTERVALL_MIN * 60000)
            TimerPMRefresh.Interval = oIntervallMS
            'ClassLogger.Add("Timer - Intervall: " & clsSQLITE.konf_intervall & " Minuten", False)
            TimerPMRefresh.Enabled = True
            Logger.Debug($"Timer PM Refresh gestartet, mit Intervall {My.Settings.PMREFRESH_INTERVALL_MIN} Minuten ")
            'End If
            If My.Settings.SQLSERVER_CS_RH = "" And My.Settings.SQLSERVER_CS_PMRefresh <> "" Then
                Logger.Info("Thread PM Refresh will now be started for initial Run as Resulthandler's ConnString is empty...")
                threadPMRefresh.RunWorkerAsync()
            Else
                If My.Settings.SQLSERVER_CS_RH <> "" Then
                    Logger.Info("Thread ResultHandler will now be started for initial Run..")
                    threadResultHandler.RunWorkerAsync()
                End If
            End If

        Catch ex As Exception
            EventLog.WriteEntry("DDWMResultHandler", "Unexpected error in OnStart: " & ex.ToString(), EventLogEntryType.Error)
            Logger.Error(ex)
        End Try

    End Sub
    Public Sub Thread_Run()
        If Not threadResultHandler.IsBusy Then
            threadResultHandler.RunWorkerAsync()
        End If
    End Sub
    Public Sub ThreadPMRefreshRun()
        Logger.Debug("In Tick of ThreadPMRefreshRun")
        If Not threadPMRefresh.IsBusy Then
            threadPMRefresh.RunWorkerAsync()
        Else
            Logger.Warn("threadPMRefresh IsBusy")
        End If
    End Sub
    Protected Overrides Sub OnStop()
        Try
            ' Hier Code zum Ausführen erforderlicher Löschvorgänge zum Beenden des Dienstes einfügen.
            Logger.Info("WindreamResultHandler wurde gestoppt!")

        Catch ex As Exception
            EventLog.WriteEntry("DDWMResultHandler", "Unexpected error in OnStop: " & ex.ToString(), EventLogEntryType.Error)
        End Try

    End Sub
    Public Sub RUN_RESULTHANDLER(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
        Try
            MyLogger = New LogConfig(LogConfig.PathType.CustomPath, Path.Combine(My.Application.Info.DirectoryPath, "Log"))
            Logger = MyLogger.GetLogger()
            _database = New clsDatabase(MyLogger)

            If My.Settings.SQLSERVER_CS_RH = "" Then
                Logger.Warn("RESULT HANDLER ConString not configured... No Run")
                Exit Sub
            End If

            Dim notcompleted As Boolean = False
            'clsLogger.Init(My.Application.Info.DirectoryPath & "\Log", "_SERVICEResultHandler")
            Logger.Debug("RUN_THREAD WMResulthandler started..")
            ' Windream instanziieren
            _windream = New clsWindream_allgemein(MyLogger)
            'windream initialisieren
            If _windream.Init() = True Then
                clsCURRENT.TEMP_FILES.Clear()
                Logger.Debug("windream vollumfänglich initialisiert!")
                'Zur sicherheit die DB nochmal initialiseren
                If _database.Init(My.Settings.SQLSERVER_CS_RH, True) = True Then
                    Dim DT As DataTable = _database.Return_Datatable("select * from TBWMRH_KONFIGURATION where GUID = 1")
                    If DT.Rows.Count = 1 Then
                        clsCURRENT.DT_TBWMRH_KONFIGURATION = DT
                        clsCURRENT.WDLAUFWERK = clsCURRENT.DT_TBWMRH_KONFIGURATION.Rows(0).Item("WD_LAUFWERK")
                        DD_WMResulthandler.clsCURRENT.DEBUG = Not (DT.Rows(0).Item("LOG_ERRORS_ONLY"))
                        MyLogger.Debug = Not (DT.Rows(0).Item("LOG_ERRORS_ONLY"))
                        If DD_WMResulthandler.clsCURRENT.DEBUG = True Then
                            Logger.Info("Detaillog is ON!")
                        End If
                        DD_WMResulthandler.clsCURRENT.WDLAUFWERK = DT.Rows(0).Item("WD_LAUFWERK")
                    End If
                    DT = _database.Return_Datatable("SELECT GUID FROM TBWMRH_PROFIL WHERE AKTIV = 1 order by REIHENFOLGE")
                    If DT.Rows.Count > 0 Then
                        Logger.Debug("Anzahl der aktiven Profile: " & DT.Rows.Count.ToString)
                        For Each DR As DataRow In DT.Rows
                            _PROFIL_ID = CInt(DR.Item("GUID"))
                            _profil = New clsProfil(MyLogger, _PROFIL_ID)
                            'Und nun das Profil durchlaufen
                            Dim initresult = _profil.Init(_PROFIL_ID, False)
                            If initresult = True Then
                                '##### Profildurchlauf ########
                                _profil.Profil_Durchlauf(False)
                                For Each oFile As String In clsCURRENT.TEMP_FILES
                                    If File.Exists(oFile) Then
                                        Try
                                            File.Delete(oFile)
                                        Catch ex As Exception

                                        End Try

                                    End If
                                Next

                            ElseIf initresult = False Then
                                Logger.Warn("clsProfil konnte nicht initialisiert werden")
                                notcompleted = True
                            ElseIf initresult = 0 Then
                                Logger.Debug("initresult: 0")
                                notcompleted = True
                            ElseIf initresult = 1 Then
                                Logger.Debug("initresult: 1")
                                notcompleted = True
                            End If
                        Next
                    Else
                        Logger.Info("WMResulthandler - No active profiles")
                        notcompleted = True
                    End If
                    'Try
                    '    For Each _file In clsCURRENT.TEMP_FILES
                    '        'Dim oFile As New FileInfo(_file)
                    '        'If (DateTime.UtcNow - oFile.CreationTimeUtc > TimeSpan.FromDays(1)) Then
                    '        System.IO.File.Delete(_file)
                    '        'End If
                    '    Next
                    'Catch ex As Exception

                    'End Try

                    _database.Execute_non_Query("UPDATE TBWMRH_KONFIGURATION SET LAST_TICK = GETDATE() WHERE GUID = 1")
                    If oFirstRun = True Then
                        oFirstRun = False
                        threadPMRefresh.RunWorkerAsync()
                    End If
                Else
                    Logger.Warn($"clsDatabase konnte nicht initialisiert werden! {My.Settings.SQLSERVER_CS_RH}")
                    notcompleted = True
                End If
            Else
                Logger.Warn("# Achtung: Windream-Init mit Fehlern beendet")
                notcompleted = True
            End If
            If notcompleted = True Then

            End If
        Catch ex As Exception
            Logger.Error(ex)
        End Try

    End Sub
    Public Sub RUNPMRefresh(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
        Try
            'MyLoggerPMR = New LogConfig(LogConfig.PathType.CustomPath, Path.Combine(My.Application.Info.DirectoryPath, "Log_PMRefresh"))
            'LoggerPMR = MyLoggerPMR.GetLogger()
            PMRefresh = New clsPMRefresh(MyLogger)
            Logger.Debug("PMRefresh.CheckRun....")
            If PMRefresh.CheckRun() = True Then
                Logger.Debug("PMRefresh.CheckRun = True....")
                PMRefresh.Refresh_Data()
            End If
        Catch ex As Exception
            Logger.Error(ex)
        End Try
    End Sub
#Region "*** BackgroundWorker beenden und Abbrechen ***"
    Private Sub Thread_Completed(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) 'Handles threadDateiimport.RunWorkerCompleted
        ' This event fires when the DoWork event completes
        Try
            Dim result As String = ""

            If e.Cancelled Then
                Logger.Warn("Der Process wurde durch den Anwender abgebrochen")

            ElseIf e.Error IsNot Nothing Then
                Logger.Warn("Fehler bei Durchlauf. Der Vorgang wird abgebrochen: " & e.Error.Message)

            End If

            'If DI_Verzeichnisloeschen Then
            '    Try
            '        My.Computer.FileSystem.DeleteDirectory(DI_Quellordner, FileIO.DeleteDirectoryOption.ThrowIfDirectoryNonEmpty)
            '    Catch ex As Exception
            '        ClassLogger.Add("ACHTUNG: Der Vorgang wurde abgeschlossen. Das Quellverzeichnis konnte jedoch nicht gelöscht werden, da sich in dem Ordner noch Dateien/Verzeichnisse befinden.", False)
            '    End Try
            'End If
        Catch ex As Exception
            EventLog.WriteEntry("DDWMResultHandler", "Unexpected error in Thread_Completed: " & ex.ToString(), EventLogEntryType.Error)
        End Try
    End Sub
    Private Sub ThreadPMRefresh_Completed(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) 'Handles threadDateiimport.RunWorkerCompleted
        ' This event fires when the DoWork event completes
        Try
            Dim result As String = ""

            If e.Cancelled Then
                Logger.Warn("Der Process PMRefresh wurde durch den Anwender abgebrochen")

            ElseIf e.Error IsNot Nothing Then
                Logger.Warn("Fehler bei Durchlauf PMRefresh. Der Vorgang wird abgebrochen: " & e.Error.Message)

            End If

            'If DI_Verzeichnisloeschen Then
            '    Try
            '        My.Computer.FileSystem.DeleteDirectory(DI_Quellordner, FileIO.DeleteDirectoryOption.ThrowIfDirectoryNonEmpty)
            '    Catch ex As Exception
            '        ClassLogger.Add("ACHTUNG: Der Vorgang wurde abgeschlossen. Das Quellverzeichnis konnte jedoch nicht gelöscht werden, da sich in dem Ordner noch Dateien/Verzeichnisse befinden.", False)
            '    End Try
            'End If
        Catch ex As Exception
            Logger.Error(ex, "Unexpected error in ThreadPMRefresh_Completed: ")

        End Try
    End Sub
    Public Function Thread_Abbrechen()
        Try
            If DDWDResultHandler.threadResultHandler.IsBusy Then
                DDWDResultHandler.threadResultHandler.CancelAsync()
            End If
            Return True
        Catch ex As Exception
            EventLog.WriteEntry("DDWMResultHandler", "Unexpected error in Thread_Abbrechen: " & ex.ToString(), EventLogEntryType.Error)
            Logger.Error(ex)

            Return False
        End Try
    End Function
#End Region
End Class
