Imports DigitalData.Modules.Logging
Imports DD_WMResulthandler
Public Class clsPMRefresh
    Private Logger As Logger
    Private Shared MyLogger As LogConfig
    Private _database As clsDatabase
    Private _windream As clsWindream_allgemein

    Private oConfigschedule
    Private oConfigIDXName_DocID
    Private oConfigIDXName_Created
    'Private oConfigWMDrive
    Private oConfigLOG_DEBUG As Boolean
    Sub New(theLogger As LogConfig)
        MyLogger = theLogger
        Logger = MyLogger.GetLogger()
    End Sub
    Public Function CheckRun() As Boolean
        Try
            _database = New clsDatabase(MyLogger)
            _windream = New clsWindream_allgemein(MyLogger)
            Logger.Debug("..in CheckRun..classes initialized")
            If _windream.Init() = True Then
                If My.Settings.SQLSERVER_CS_PMRefresh = "" Then
                    Logger.Info("SQLSERVER_CS_PMRefresh is empty!")
                    Return False
                End If
                If _database.Init(My.Settings.SQLSERVER_CS_PMRefresh, False) = True Then
                    Dim oDTPM_CONFIG As DataTable = _database.Return_Datatable("select * from TBPM_KONFIGURATION where GUID = 1", My.Settings.SQLSERVER_CS_PMRefresh)
                    If oDTPM_CONFIG.Rows.Count = 1 Then
                        oConfigschedule = oDTPM_CONFIG.Rows(0).Item("SERVICE_SCHEDULE").ToString
                        oConfigIDXName_DocID = oDTPM_CONFIG.Rows(0).Item("SERVICE_IDXNAME_DOCID").ToString
                        oConfigIDXName_Created = oDTPM_CONFIG.Rows(0).Item("SERVICE_IDXNAME_CREATED").ToString
                        'oConfigWMDrive = oDTPM_CONFIG.Rows(0).Item("SERVICE_WMDRIVE_LETTER").ToString
                        oConfigLOG_DEBUG = Not (oDTPM_CONFIG.Rows(0).Item("SERVICE_LOG_ERRORS_ONLY"))
                        Dim oSplit As String()
                        oSplit = oConfigschedule.Split(";")
                        Dim oTimespan = oSplit(0)
                        Dim oDays = oSplit(1)
                        If oConfigLOG_DEBUG = True Then
                            MyLogger.Debug = True
                            Logger.Info("Detaillog Service PMRefresh is ON!")
                        Else
                            MyLogger.Debug = False
                        End If

                        Dim oDayofweek As Integer = My.Computer.Clock.LocalTime.DayOfWeek
                        Dim oSubstringInteger As Integer = 0
                        Dim oRunToday As Integer = 0
                        Select Case oDayofweek
                            Case 6 'Saturday
                            Case 5 'Friday
                            Case 4 'Thursday
                            Case 3 'Wednesday
                            Case 2 'Tuesday
                            Case 1 'Monday
                            Case 0 'Sunday
                        End Select
                        Logger.Debug($"oDayofweek: {oDayofweek}...")

                        If oDayofweek = 0 Then
                            oSubstringInteger = 6
                        Else
                            oSubstringInteger = oDayofweek - 1
                        End If
                        Logger.Debug($"oSubstringInteger: {oSubstringInteger}...")
                        oRunToday = oDays.Substring(oSubstringInteger, 1)
                        Logger.Debug($"oRunToday: {oRunToday}...")
                        If oRunToday = 1 Then
                            Dim oHourSplit As String() = oTimespan.Split("-")
                            Dim oMinHour As Integer = oHourSplit(0)
                            Dim oMaxHour As Integer = oHourSplit(1)
                            If CInt(Now.Hour) >= oMinHour And CInt(Now.Hour) < oMaxHour Then
                                Logger.Debug($"Now running PM-Refresh ({oMinHour.ToString}#{oMaxHour.ToString})")
                                Return True
                            Else
                                Logger.Info($"No run of PMRefresh as hour is not in timespan ({CInt(Now.Hour)} >= {oMinHour} And {CInt(Now.Hour)} < {oMaxHour})")
                                Logger.Info($"Check TBPM_KONFIGURATION Column SERVICE_SCHEDULE")

                            End If
                        Else
                            Logger.Info($"No run of PMRefresh as today Is Not configured as RUN")
                        End If
                    Else
                        Logger.Warn("oDTPM_CONFIG.Rows.Count <> 1")
                    End If
                Else
                    Logger.Warn($"Could not initialize the database of PMRefresh ConString: '{My.Settings.SQLSERVER_CS_PMRefresh}'")
                End If
            Else
                Logger.Warn("Could not initialize windream in PMRefresh.")
            End If
            'Return false as no criteria matched to execute the run
            Return False
        Catch ex As Exception
            Logger.Info("Unexpected Error in CheckRun")
            Logger.Error(ex)
            Return False
        End Try

    End Function
    Public Function GetSearchDocumentsDTviaSQL(ByVal pSQLCommand As String) As DataTable
        Dim dtresult As New DataTable
        dtresult.Columns.Add("DOC_ID", GetType(Integer))
        dtresult.Columns.Add("PATH", GetType(String))
        dtresult.Columns.Add("CREATED", GetType(String))

        Try
            Dim oSQLRESULT As DataTable = _database.Return_Datatable(pSQLCommand)
            If IsNothing(oSQLRESULT) Then
                Return dtresult
            End If
            'If returnDT = True Then
            If oSQLRESULT.Rows.Count > 0 Then

                For Each oDocRow As DataRow In oSQLRESULT.Rows
                    Dim oDOC_ID As Int64
                    Try
                        oDOC_ID = oDocRow.Item("IDB_OBJ_ID")
                    Catch ex As Exception
                        Try
                            oDOC_ID = oDocRow.Item("DocID")
                        Catch ex1 As Exception
                            Logger.Warn("Could not get DocID-Column: " & ex.Message)
                            Return dtresult
                        End Try
                    End Try
                    Dim oCreated
                    Try
                        oCreated = oDocRow.Item("ADDED_WHEN")
                    Catch ex As Exception
                        Try
                            oCreated = oDocRow.Item("AddedWhen")
                        Catch ex1 As Exception
                            Logger.Warn($"(GetSearchDocumentsDTviaSQL)Could not get AddedWhen-Column: [{ex.Message}] - SQL-Command: [{pSQLCommand}]")
                            Return dtresult
                        End Try
                    End Try

                    Dim oPath As String
                    Try
                        oPath = oDocRow.Item("DocRelativePath")
                    Catch ex As Exception
                        Try
                            oPath = oDocRow.Item("FULL_FILENAME")
                        Catch ex1 As Exception
                            Logger.Warn($"(GetSearchDocumentsDTviaSQL)Could not get FULL_FILENAME-Column: [{ex.Message}] - SQL-Command: [{pSQLCommand}]")
                            Return dtresult
                        End Try
                    End Try
                    Logger.Debug($"Adding DocInfo {oDOC_ID.ToString}|{oPath}|{oCreated}")
                    dtresult.Rows.Add(oDOC_ID, oPath, oCreated)
                Next
                dtresult.AcceptChanges()
            End If
            Return dtresult
        Catch ex As Exception
            Logger.Error(ex)
            Logger.Warn($"Error Getting Docs via SLQ ({pSQLCommand})")
            Return dtresult
        End Try
    End Function

    Public Function Refresh_Data()
        Dim oStep As String
        Try
            Logger.Debug("Check_Profiles gestartet", False)
            Dim WD_Search As String
            Dim oSQLCommand As String
            oSQLCommand = "SELECT GUID,NAME,WD_OBJECTTYPE,WD_SEARCH FROM TBPM_PROFILE WHERE ACTIVE = 1"
            oStep = 1
            Dim oDTPROFILES As DataTable = _database.Return_Datatable(oSQLCommand, My.Settings.SQLSERVER_CS_PMRefresh)
            oStep = 2
            '---------------------- Evtl alte nicht aktualisierte PROFILE-FILE Daten werden gelöscht ------------------------
            Dim oDelete As String = "DELETE FROM TBPM_PROFILE_FILES WHERE ACTIVE = 0 AND IN_WORK = 0"
            _database.Execute_non_Query(oDelete, My.Settings.SQLSERVER_CS_PMRefresh)

            oSQLCommand = "select * from TBPM_PROFILE_FILES"
            Dim oDTPROFILE_FILES As DataTable = _database.Return_Datatable(oSQLCommand, My.Settings.SQLSERVER_CS_PMRefresh)
            If oDTPROFILE_FILES.Rows.Count = 0 Then
                Logger.Info("TBPM_PROFILE_FILES is completely empty...")
            End If
            'delete = "DELETE FROM TBPM_PROFILE_FILES_TEMP"
            'ClassDatabase.Execute_MSSQL(delete)
            oStep = 3

            If oDTPROFILES.Rows.Count > 0 Then
                Dim Profile_Row As System.Data.DataRow
                '---------------------- für jedes Profil die Dateien überprüfen ------------------------
                For Each Profile_Row In oDTPROFILES.Rows
                    oStep = "4a"
                    Logger.Debug("Add info for profile '" & Profile_Row.Item("NAME") & "'")
                    Dim oPROFILE_ID As Integer = Profile_Row.Item("GUID")
                    WD_Search = Nothing
                    WD_Search = Profile_Row.Item("WD_SEARCH")
                    oStep = "4b"
                    If WD_Search Is Nothing = False Then
                        '---------------------- Die Dateien auslesen ------------------------
                        Dim oDTWM_Results As DataTable
                        oStep = "4c"
                        If WD_Search.Contains("wdf") Or WD_Search.Contains("wdfx") Then
                            oDTWM_Results = _windream.GetSearchDocumentsDT(WD_Search, oConfigIDXName_DocID, oConfigIDXName_Created, True)
                        Else
                            Logger.Debug("Search via SQL")
                            oDTWM_Results = GetSearchDocumentsDTviaSQL(WD_Search)
                        End If

                        oStep = "4d"
                        Dim oDocCount As Integer = 0
                        If IsNothing(oDTWM_Results) Then
                            Logger.Warn("ATTENTION: oDTWM_Results is NOTHING")
                            Continue For
                        End If
                        'Die aktuellen Files auf refreshed = 0 setzten
                        oSQLCommand = "UPDATE TBPM_PROFILE_FILES SET REFRESHED = 0 WHERE PROFIL_ID = " & oPROFILE_ID
                        If _database.Execute_non_Query(oSQLCommand, My.Settings.SQLSERVER_CS_PMRefresh) = True Then
                            If oDTWM_Results Is Nothing = False Then
                                If oDTWM_Results.Rows.Count > 0 Then
                                    oStep = "4e"
                                    'Ein Array mit Dateiinformationen anlegen
                                    Dim Profil_Docs(oDTWM_Results.Rows.Count - 1, 2) As String
                                    For Each oRow As DataRow In oDTWM_Results.Rows
                                        Dim oDOC_ID = oRow.Item(0)
                                        Dim oWMFilePath As String = oRow.Item(1)
                                        Profil_Docs(oDocCount, 0) = oRow.Item(0)
                                        Profil_Docs(oDocCount, 1) = oWMFilePath
                                        '------DMS Erstell-Datum holen --------
                                        Dim oDMSErstellt = oRow.Item(2)


                                        'ClassLogger.Add(">> DMSErstellt: '" & DMSErstellt.ToString, False)
                                        Dim date_EN As String
                                        If oConfigIDXName_Created.EndsWith("reated") Then
                                            Dim arr() = oDMSErstellt.ToString.Split(".")
                                            If arr.Length = 3 Then
                                                date_EN = arr(2).Replace(" 00:00:00", "") & "-" & arr(1) & "-" & arr(0)
                                                Logger.Debug("date_EN: '" & date_EN)
                                                oDMSErstellt = date_EN
                                            End If
                                        End If
                                        '-------------------- Überprüfen ob das Dokument bereits enthalten ist? Kann nur passieren wenn das Dok gerade in Bearbeitung ist ----------
                                        oSQLCommand = $"SELECT GUID FROM TBPM_PROFILE_FILES WHERE PROFIL_ID =  {oPROFILE_ID} AND DOC_ID = {oDOC_ID}"
                                        Dim oGUID = _database.Execute_Scalar(oSQLCommand, My.Settings.SQLSERVER_CS_PMRefresh)
                                        '---------------------- Das Dokument inserten ------------------------
                                        Try
                                            If oGUID Is Nothing Or oDTPROFILE_FILES.Rows.Count = 0 Then
                                                Logger.Debug($"DocID {oDOC_ID} not existing...INSERT")
                                                Dim oInsert As String = $"INSERT INTO TBPM_PROFILE_FILES (PROFIL_ID, FILE_PATH, ACTIVE, DMS_ERSTELLT_DATE,DOC_ID) VALUES ({oPROFILE_ID}, '{oWMFilePath}',1, CONVERT(DATE,'{oDMSErstellt}'),{oDOC_ID})"
                                                If _database.Execute_non_Query(oInsert, My.Settings.SQLSERVER_CS_PMRefresh) = False Then
                                                    Logger.Info($"Unexpected Error while Inserting File-Record {oDOC_ID}")
                                                End If
                                                ' aktuelles Dokument der Klasse mitteilen
                                            Else
                                                Logger.Debug($"DocID {oDOC_ID} existing...UPDATE")
                                                If CInt(oGUID) > 0 Then
                                                    oSQLCommand = $"UPDATE TBPM_PROFILE_FILES SET REFRESHED = 1, REFRESHED_WHEN = GETDATE(), EDIT = 0 WHERE GUID = {oGUID}"
                                                    _database.Execute_non_Query(oSQLCommand, My.Settings.SQLSERVER_CS_PMRefresh)
                                                End If

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

                                        oDocCount += 1
                                    Next

                                    Logger.Info($"Profile [{Profile_Row.Item("NAME")}] refreshed - FileCount [{oDocCount.ToString}]")

                                Else
                                    oStep = "4g"
                                    Logger.Debug($"No Data for profile '{Profile_Row.Item("NAME")}'!")
                                End If
                            Else
                                Logger.Warn("oDTWM_Results IS NOTHING")
                            End If
                            oStep = "Step: vor Delete Refreshed = 0"
                            Dim oSQLDEL As String = "DELETE FROM TBPM_PROFILE_FILES WHERE PROFIL_ID = " & oPROFILE_ID & " AND REFRESHED = 0"
                            _database.Execute_non_Query(oSQLDEL, My.Settings.SQLSERVER_CS_PMRefresh)
                            '---------------------- Aktuelle Anzahl in Profiltabelle updaten ------------------------
                            oSQLCommand = $"UPDATE TBPM_PROFILE SET NO_OF_DOCUMENTS = {oDocCount} WHERE GUID = {oPROFILE_ID}"
                            oStep = "Step 4h AnzahlDocs: - " & oDocCount.ToString
                            _database.Execute_non_Query(oSQLCommand, My.Settings.SQLSERVER_CS_PMRefresh)

                        Else
                            Logger.Warn("ATTENTION: Refresh could not be executed " & oSQLCommand)
                        End If
                    Else
                        Logger.Warn("ATTENTION: WM-Search is nothing.. ")
                    End If
                Next
                oStep = "4i"
                ''------------------------------- Bearbeitete Daten löschen ------------------------
                If _database.Execute_non_Query("DELETE FROM TBPM_PROFILE_FILES WHERE EDIT = 1", My.Settings.SQLSERVER_CS_PMRefresh) = True Then
                    '    oStep = "i"
                    '    Console.WriteLine(">> Alte PROFILE-FILE Daten geleert")
                    '    '---------------------- DIE NEUEN DATEN AUF ACTIVE SETZEN ------------------------
                    '    Dim update As String = "UPDATE TBPM_PROFILE_FILES SET ACTIVE = 1 WHERE ACTIVE = 0"
                    '    ClassDatabase.Execute_MSSQL(update)
                    '    oStep = "j"
                    '    Console.WriteLine(">> Neue PROFILE-FILE Daten aktiv gesetzt")
                End If
                oStep = "4j"
                _database.Execute_non_Query("EXEC PRPM_REMOVE_NE_FILES", My.Settings.SQLSERVER_CS_PMRefresh)
                oStep = "4k"
            Else
                Logger.Info("PM Refresh - No active profiles")
            End If

        Catch ex As Exception
            Logger.Info("Unexpected Error in Refresh_Data")
            Logger.Warn("Error in RunJob- laststep: " & oStep)
            Logger.Error(ex)
        End Try
    End Function
End Class
