Imports DigitalData.EMLProfiler.ClassCurrent
Imports Independentsoft.Email.Mime
Imports DigitalData.Modules.Logging
Public Class clsWorker
    Private Shared Logger As Logger
    Private MyLogger As LogConfig
    Private _email As clsEmail
    Private _emailIMAP As clsEmailIMAP
    Private _Database As clsDatabase
    Private _USE_WM As Boolean = False
    Private _windream As clsWindream_allgemein
    Private _windream_index As clsWindream_Index
    Private _workmail As clsWorkEmail
    Private _wrapper As clsEncryption
    Private _POLL_PROFILEID As Integer = 0
    Dim cs As String
    Sub New(LogConf As LogConfig, ConStr As String, POLL_PROFILEID As Integer, FB_DATASOURCE As String, FB_DATABASE As String, FB_USER As String, FB_PW As String, USE_WM As Boolean, Optional plocaleml As String = "")
        Logger = LogConf.GetLogger
        _email = New clsEmail(LogConf)
        _emailIMAP = New clsEmailIMAP(LogConf, ConStr)
        _Database = New clsDatabase(LogConf, ConStr)
        cs = ConStr
        _USE_WM = USE_WM
        If _USE_WM Then
            _windream = New clsWindream_allgemein(LogConf)
            _windream_index = New clsWindream_Index(LogConf)
        End If

        _workmail = New clsWorkEmail(LogConf, ConStr, FB_DATASOURCE, FB_DATABASE, FB_USER, FB_PW, USE_WM)
        _wrapper = New clsEncryption("!35452didalog=", LogConf)
        _POLL_PROFILEID = POLL_PROFILEID
        ClassCurrent.CURRENT_DEBUG_LOCAL_EMAIL = plocaleml
    End Sub

    Public Sub Debug_Local_Email()
        Try

        Catch ex As Exception

        End Try
    End Sub

    Public Sub Start_WorkingProfiles(Optional LocalEmail As Boolean = False)
        Try
            TEMP_FILES.Clear()

            If _Database.Init(cs) = True Then
                Logger.Debug("now windream_init... ")
                If _USE_WM Then
                    If _windream.Init = False Then
                        Logger.Info("windream could not be initialized!!")
                        Exit Sub
                    Else
                        Logger.Debug("windream_initialized!")
                    End If
                End If
                Dim osql As String = "SELECT * FROM TBEMLP_POLL_PROFILES"
                If _POLL_PROFILEID = 0 Then
                    osql &= " WHERE ACTIVE = 1 order by SEQUENCE"
                Else
                    osql &= " WHERE GUID = " & _POLL_PROFILEID
                    End If
                Dim DT_TBDD_EMAIL As DataTable = _Database.Return_Datatable("SELECT * FROM TBDD_EMAIL_ACCOUNT WHERE ACTIVE = 1")
                Dim DT_PROFILES = _Database.Return_Datatable(osql)
                    If Not IsNothing(DT_PROFILES) Then
                    If DT_PROFILES.Rows.Count > 0 Then
                        Logger.Debug("count of active profiles: " & DT_PROFILES.Rows.Count.ToString)
                        For Each oDR_Profile As DataRow In DT_PROFILES.Rows
                            CURRENT_PROFILE_GUID = oDR_Profile.Item("GUID")
                            DT_POLL_PROCESS = Nothing
                            Dim sql = String.Format("SELECT * FROM TBEMLP_POLL_PROCESS WHERE PROFILE_ID = {0} AND ACTIVE = 1", CURRENT_PROFILE_GUID)
                            DT_POLL_PROCESS = _Database.Return_Datatable(sql)
                            If Not IsNothing(DT_POLL_PROCESS) Then
                                If DT_POLL_PROCESS.Rows.Count = 0 Then
                                    Logger.Info("No processes configured for this Email-Profile - " & sql)
                                    Continue For
                                Else
                                    DT_STEPS = Nothing
                                    DT_STEPS = _Database.Return_Datatable(String.Format("SELECT T.* FROM TBEMLP_POLL_STEPS T,TBEMLP_POLL_PROCESS T1  WHERE T.PROCESS_ID = T1.GUID AND T1.PROFILE_ID = {0} AND T1.ACTIVE = 1", CURRENT_PROFILE_GUID))

                                End If
                            Else
                                Logger.Warn("DT_POLL_PROCESS is nothing")
                                Continue For
                            End If

                            CURRENT_EMAIL_GUID = 0
                            MAIL_FROM = ""
                            MAIL_SERVER = ""
                            MAIL_USER = ""
                            MAIL_USER_PW = ""

                            CURRENT_POLL_TYPE = oDR_Profile.Item("POLL_TYPE")
                            Logger.Debug(String.Format("Working on profile: ({0}-{1}-{2}) ", oDR_Profile.Item("GUID"), oDR_Profile.Item("PROFILE_NAME"), CURRENT_POLL_TYPE))
                            CURRENT_EMAIL_GUID = oDR_Profile.Item("EMAIL_CONF_ID")

                            Dim EMAIL_PROF_TABLE As DataTable = DT_TBDD_EMAIL
                            'Presuming the DataTable has a column named Date.
                            Dim expression As String
                            expression = "GUID = " & CURRENT_EMAIL_GUID
                            Logger.Debug("Expression Filter email: " & expression)
                            Logger.Debug("DT_TBDD_EMAIL.rowCount: " & DT_TBDD_EMAIL.Rows.Count)
                            'Filter the rows using Select() method of DataTable
                            Dim FilteredRows As DataRow() = EMAIL_PROF_TABLE.Select(expression)
                            If FilteredRows.Length = 1 Then
                                For Each row As DataRow In FilteredRows
                                    MAIL_FROM = row("EMAIL_FROM")
                                    MAIL_SERVER = row("EMAIL_SMTP")
                                    MAIL_USER = row("EMAIL_USER")
                                    MAIL_USER_PW = row("EMAIL_PW")
                                    MAIL_PORT = row("PORT_IN")
                                    MAIL_INBOX_NAME = "Inbox"
                                    MAIL_ARCHIVE_FOLDER = row("ARCHIVE_FOLDER")
                                    Logger.Debug(String.Format("{0}-{1}", MAIL_FROM, MAIL_SERVER))

                                    Dim PWPlain = _wrapper.DecryptData(MAIL_USER_PW)
                                    If Not IsNothing(PWPlain) Then
                                        If PWPlain <> "" Then
                                            MAIL_USER_PW = PWPlain
                                        Else
                                            Logger.Warn("PWPlain is string.empty - Could not decrypt passwort")
                                        End If
                                    Else
                                        Logger.Warn("PWPlain is nothing - Could not decrypt passwort")
                                    End If

                                Next
                                CURRENT_WORKMAIL_LIST.Clear()

                                If MAIL_SERVER <> "" Then
                                    Dim pollresult As Boolean = False
                                    If LocalEmail = True Then
                                        pollresult = True
                                        Dim oMessage As New Message(CURRENT_DEBUG_LOCAL_EMAIL)
                                        CURRENT_WORKMAIL_LIST.Add(oMessage)
                                    Else
                                        Select Case CURRENT_POLL_TYPE
                                            Case "POP"
                                                pollresult = _email.POP3_COLLECT()
                                            Case "IMAP"
                                                'pollresult = _emailIMAP.IMAP_COLLECT()
                                                'pollresult = _emailIMAP.FetchIMAPMessagesIsoft(MAIL_SERVER, MAIL_PORT, MAIL_USER, MAIL_USER_PW, MAIL_INBOX_NAME, MAIL_ARCHIVE_FOLDER)
                                                pollresult = _emailIMAP.FetchIMAPMessagesS22(MAIL_SERVER, MAIL_PORT, MAIL_USER, MAIL_USER_PW, MAIL_INBOX_NAME)
                                        End Select
                                    End If

                                    'If pollresult = False Then
                                    '    Logger.Info(String.Format("Error while polling emails...Trying S22...."))
                                    '    pollresult = _emailIMAP.FetchIMAPMessages(MAIL_SERVER, MAIL_PORT, MAIL_USER, MAIL_USER_PW, MAIL_INBOX_NAME)
                                    '    If pollresult = False Then
                                    '        Logger.Warn(String.Format("FetchIMAPMessagesS22 - also returned error!"))
                                    '    End If
                                    'End If
                                    If CURRENT_WORKMAIL_LIST.Count() > 0 Then
                                        Logger.Info(String.Format("Worked/Pulled: [{0}] E-Mails", CURRENT_WORKMAIL_LIST.Count()))
                                        Try
                                            For Each pulled_msg As Message In CURRENT_WORKMAIL_LIST
                                                _workmail.WorkEmailMessage(pulled_msg)
                                                CURRENT_MAIL_MESSAGE = Nothing
                                            Next
                                        Catch ex As Exception
                                            Logger.Error(ex)
                                            Logger.Warn($"Error converting CURRENT_WORKMAIL_LIST to IsoftMesage: {ex.Message} ")
                                        End Try

                                    Else
                                        Logger.Debug(String.Format("No emails for profile!"))
                                    End If
                                Else
                                    Logger.Warn("For the Email-Profile ID " & CURRENT_EMAIL_GUID & " no record could be found!")
                                End If

                                _Database.Execute_non_Query("UPDATE TBEMLP_POLL_PROFILES SET LAST_TICK = GETDATE() WHERE GUID = " & oDR_Profile.Item("GUID").ToString)
                            Else
                                Logger.Warn("For the Email-Profile ID " & CURRENT_EMAIL_GUID & " no record could be found! Check wether Email-Profile is active!")
                            End If
                        Next
                        Try
                            'Delete all Tempfiles
                            For Each _file In TEMP_FILES
                                Logger.Debug("Trying to delete temp file: [{0}]", _file)

                                If System.IO.File.Exists(_file) Then
                                    Try
                                        System.IO.File.Delete(_file)
                                    Catch ex As Exception
                                        Logger.Error(ex)
                                        Logger.Warn($"TempFileDelete - Could not delete the tempfile from TEMP_FILES: {ex.Message}")
                                    End Try
                                End If
                            Next
                            'Try
                            '    Dim oDiTempPath As New IO.DirectoryInfo(System.IO.Path.GetTempPath)
                            '    Dim oaryFi As IO.FileInfo() = oDiTempPath.GetFiles()
                            '    Dim ofi As IO.FileInfo

                            '    For Each fi In oaryFi
                            '        Try
                            '            fi.Delete()
                            '        Catch ex As Exception
                            '            Logger.Warn($"TempFileDelete2 - Could not delete the tempfile: {ex.Message}")
                            '        End Try

                            '    Next
                            'Catch ex As Exception
                            '    Logger.Warn($"TempFileDelete3 - Could not delete the tempfile: {ex.Message}")
                            'End Try


                        Catch ex As Exception
                            Logger.Warn($"TempFileDelete(X) - Could not delete the tempfile from TEMP_FILES: {ex.Message}")
                        End Try

                    Else
                        Logger.Info("No active profiles")
                        End If
                    End If

                    _Database.Execute_non_Query("UPDATE TBEMLP_CONFIG SET LAST_TICK = GETDATE() WHERE GUID = 1")
            End If
        Catch ex As Exception
            Logger.Error(ex)
        End Try
    End Sub
End Class
