Imports System.IO
Imports System.Text.RegularExpressions
Imports DigitalData.Modules.Config
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Logging
Imports EmailProfiler.Common
Imports GdPicture14
Imports Message = Independentsoft.Email.Mime.Message
Imports Attachment = Independentsoft.Email.Mime.Attachment
Imports LicenseManager = GdPicture14.LicenseManager


Public Class Form1
    Private _logger As Logger
    Private Shared _MyLogger As LogConfig
    Private _Worklist As List(Of String)
    Private MyDatabase As MSSQLServer

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            _MyLogger = New LogConfig(LogConfig.PathType.CustomPath, Path.Combine(My.Application.Info.DirectoryPath, "Log"), Nothing, My.Application.Info.CompanyName, My.Application.Info.ProductName)
            _logger = _MyLogger.GetLogger()
            _MyLogger.Debug = True

            Dim dbResult As Boolean

            If My.Settings.DD_ECM_CONSTRING = String.Empty Then
                MsgBox("No Databaseconnection configured. (First Start or Appdata not accessible)" & vbNewLine & "Basic-Config will be loaded.", MsgBoxStyle.Information)
                Exit Sub
            End If

            MyDatabase = New MSSQLServer(_MyLogger, My.Settings.DD_ECM_CONSTRING)
            If MyDatabase.DBInitialized = True Then

                dbResult = True
            Else
                dbResult = False
            End If
            bsitemppath.Caption = My.Settings.Temppath
            bsifolderbrowser.Caption = My.Settings.CURR_CHECK_PATH
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in FormLoad")
        End Try

    End Sub

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
        With FolderBrowserDialog1
            .SelectedPath = My.Settings.CURR_CHECK_PATH
        End With

        If (FolderBrowserDialog1.ShowDialog() = DialogResult.OK) Then
            bsifolderbrowser.Caption = FolderBrowserDialog1.SelectedPath
            My.Settings.CURR_CHECK_PATH = bsifolderbrowser.Caption
            My.Settings.Save()
        End If

    End Sub
    Private Sub BarButtonItem3_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem3.ItemClick
        With FolderBrowserDialog1
            .SelectedPath = My.Settings.Temppath
        End With
        If (FolderBrowserDialog1.ShowDialog() = DialogResult.OK) Then
            bsitemppath.Caption = FolderBrowserDialog1.SelectedPath
            My.Settings.Temppath = FolderBrowserDialog1.SelectedPath
            My.Settings.Save()
        End If
    End Sub

    Private Sub btRunEmailCheck_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btRunEmailCheck.ItemClick
        ' Check Email
        ListBox1.Items.Clear()

        If bsifolderbrowser Is Nothing Or String.IsNullOrEmpty(bsifolderbrowser.Caption) Then
            MsgBox("Es wurde kein input-Verzeichnis konfiguriert. Abbruch!", MsgBoxStyle.Information)
            Return
        End If

        Dim di As New DirectoryInfo(bsifolderbrowser.Caption)
        ' Get a reference to each file in that directory.
        Dim fiArr As FileInfo() = di.GetFiles()
        ' Display the names of the files.
        Dim fri As FileInfo
        For Each fri In fiArr
            Try
                If Not fri.Name.EndsWith("eml") Then
                    Continue For
                End If

                Dim oList As New List(Of String)
                oList.Add(fri.FullName)
                Dim oMessage As New Message(fri.FullName)
                Dim oMSGID = oMessage.MessageID
                oMSGID = oMSGID.Replace(">", "").Replace("<", "")
                ListBox1.Items.Add($"Working on email from: {oMessage.From.EmailAddress}...Subject: {oMessage.Subject}")
                Dim oCount As Integer = 0

                For Each oAttachment As Attachment In oMessage.GetAttachments
                    Dim oString As String
                    Dim oATTFilename = oAttachment.GetFileName.ToString.ToLower
                    Dim oValidExt As Boolean = False
                    If oATTFilename.EndsWith("pdf") Then
                        oValidExt = True
                    ElseIf oATTFilename.EndsWith("xls") Then
                        oValidExt = True
                    ElseIf oATTFilename.EndsWith("xlsx") Then
                        oValidExt = True
                    ElseIf oATTFilename.EndsWith("doc") Then
                        oValidExt = True
                    ElseIf oATTFilename.EndsWith("docx") Then
                        oValidExt = True
                    ElseIf oATTFilename.EndsWith("ppt") Then
                        oValidExt = True
                    ElseIf oATTFilename.EndsWith("pptx") Then
                        oValidExt = True
                    End If
                    If oValidExt = False Then
                        Continue For
                    End If
                    oCount += 1
                    If oCount = 1 Then
                        Continue For
                    End If
                    Dim oAttachmentFileString As String = ""
                    oString = String.Format("  Working on Attachment [{0}]", oAttachment.GetFileName)
                    _logger.Info(oString)
                    ListBox1.Items.Add(oString)
                    Try
                        Dim oFilename = oAttachment.GetFileName
                        oFilename = CleanInput(oFilename)
                        _logger.Debug($"oFilename [{oFilename}]")
                        If oFilename = String.Empty Then
                            oFilename = oAttachment.GetFileName
                        End If
                        Dim oAttFilenameonly = $"{oMSGID}~{oFilename}"
                        oAttachmentFileString = Path.Combine(bsitemppath.Caption, oAttFilenameonly)
                        _logger.Debug($"oAttachmentFileString [{oAttachmentFileString}]")
                        Dim oSQL = $"SELECT * FROM IDB.DBO.TBIDB_DOC_INFO WHERE FILENAME_EXT = '{oAttFilenameonly}'"
                        Dim oDT As DataTable = MyDatabase.GetDatatable(oSQL)
                        If Not IsNothing(oDT) Then
                            If oDT.Rows.Count = 0 Then
                                oString = "  ## Attachment NOT EXISTING ##"
                                _logger.Info(oString)
                                ListBox1.Items.Add(oString)
                                If File.Exists(oAttachmentFileString) = False Then
                                    _logger.Debug(String.Format("Trying to save attachment [{0}]", oAttachmentFileString))
                                    Try
                                        oAttachment.Save(oAttachmentFileString)
                                        Dim oFileInfo As New FileInfo(oAttachmentFileString)
                                        Dim oFileLenth As Long = oFileInfo.Length
                                        If oFileLenth > 0 Then
                                            _logger.Info(String.Format("  Attachment saved to [{0}]", oAttachmentFileString))
                                        Else
                                            _logger.Warn($"##!! oFileLenth for AttachmentObjects is 0 !!##")
                                            Try
                                                File.Delete(oAttachmentFileString)
                                            Catch ex As Exception
                                                _logger.Error(ex)
                                            End Try
                                        End If

                                    Catch ex As Exception
                                        _logger.Warn($"Error while saving attachment-name: {ex.Message} - AttachmentName: {oAttachmentFileString}")
                                    End Try
                                Else
                                    ListBox1.Items.Add("EXATTMNT - Attachment (" & oAttachmentFileString & ") already existing!")
                                    _logger.Info("EXATTMNT - Attachment (" & oAttachmentFileString & ") already existing!", False, "EXTRACT_ATTACHMENTS")
                                End If
                            Else
                                oString = "  ALL OK! EXISTING"
                                _logger.Info(oString)
                                ListBox1.Items.Add(oString)
                            End If
                        End If


                    Catch ex As Exception
                        _logger.Warn($"Error while creating and saving attachment-name: {ex.Message} - AttachmentName: {oAttachmentFileString}")

                    End Try
                    oMessage = Nothing
                Next

            Catch ex As Exception
                _logger.Error(ex)
            End Try


        Next fri
    End Sub
    Private Function CleanInput(strIn As String) As String
        ' Replace invalid characters with empty strings.
        Try
            Return Regex.Replace(strIn, "[^\w\.@-]", "")
            ' If we timeout when replacing invalid characters, 
            ' we should return String.Empty.
        Catch ex As Exception
            _logger.Error(ex)
            Return String.Empty
        End Try
    End Function

    Private Sub btExtractPdfAttachments_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem4.ItemClick
        ' FileOpen Dialog
        Dim fileOpenDlg = OpenFileDialog1

        If fileOpenDlg.ShowDialog() = DialogResult.OK Then
            Dim oFilename = fileOpenDlg.FileName

            ' Call Extract Method
            ExtractEmbeddedPDFAttachments(oFilename)

        End If

    End Sub
    Private Sub ExtractEmbeddedPDFAttachments(pFilename As String)
        Try

            Dim GDPictureLicense As String = ConfigDbFunct.GetProductLicense("GDPICTURE", "11.2024", _MyLogger, My.Settings.DD_ECM_CONSTRING)

            Dim oValidExtensions = New List(Of String) From {"pdf", "xls", "xlsx", "doc", "docx", "ppt", "pptx"}
            Dim oGraphicExtensions = New List(Of String) From {"jpg", "bmp", "jpeg", "gif", "png", "xml"}

            Dim oFileInfo As New FileInfo(pFilename)

            If oFileInfo.Extension.ToLower = ".pdf" Then
                Dim oPDFConsistent As Boolean = True
                Dim oLicenseManager As New LicenseManager
                oLicenseManager.RegisterKEY(GDPictureLicense)

                Dim oGdPicturePDF As New GdPicturePDF()
                ' Lic
                Dim oStatus As GdPictureStatus = oGdPicturePDF.LoadFromFile(pFilename, True)
                If oStatus <> GdPictureStatus.OK Then
                    oPDFConsistent = False
                    Dim oResult = $"PDF-Consistency of attached file {pFilename} is not ok. ({oStatus.ToString})"
                Else
                    Dim embeddedFileCount As Integer = oGdPicturePDF.GetEmbeddedFileCount()
                    If embeddedFileCount > 0 Then
                        For i As Integer = 0 To embeddedFileCount - 1
                            Dim oEmbAttName As String = oGdPicturePDF.GetEmbeddedFileName(i)
                            Dim fileDetail As IO.FileInfo
                            fileDetail = My.Computer.FileSystem.GetFileInfo(oEmbAttName)
                            If oGdPicturePDF.GetStat() = GdPictureStatus.OK Then
                                Dim FileSize As Integer = oGdPicturePDF.GetEmbeddedFileSize(i)
                                Dim oValidExt = oValidExtensions.Any(Function(ext) oEmbAttName.EndsWith(ext))

                                If oValidExt = False Then
                                    _logger.Info("Invalid FileExtension of embedded file [{0}]", oEmbAttName)
                                    Dim GraphicExt = oGraphicExtensions.Any(Function(ext) oEmbAttName.EndsWith(ext))
                                    If GraphicExt = False Then
                                        Dim oInfo = $"Consistency or extension of attached file [{oEmbAttName}] is not ok."

                                    End If
                                    Continue For
                                End If
                                If oGdPicturePDF.GetStat() = GdPictureStatus.OK Then
                                    Dim FileData As Byte() = New Byte(FileSize) {}
                                    Dim status As GdPictureStatus = oGdPicturePDF.ExtractEmbeddedFile(0, FileData)
                                    If status <> GdPictureStatus.OK Or FileSize = 0 Then
                                        oPDFConsistent = False

                                        Dim oResult = $"Consistency or PDF-State of embedded file [{oEmbAttName}] is not ok."

                                        Continue For
                                    End If
                                End If
                            End If
                        Next
                    End If
                End If
            End If


        Catch ex As Exception
            _logger.Error(ex)


        End Try
    End Sub

    Private Sub btExtractMailAttachments_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btExtractMailAttachments.ItemClick
        ' Hier verarbeiten wir eine ausgewählte EML-Datei
        ' und speichern alle Anhänge auf die Platte.
        ' Der Einstieg und der Ablauf entspricht dem des Services.
        ' Unterschied ist die lokale Datei

        'Dim connectionString As String = "Server=SDD-VMP04-SQL17\DD_DEVELOP01;Database=DD_ECM;User Id=sa;Password=dd"
        Dim connectionString As String = "Server=SDD-VHP04-SQL19\DD_TESTING01;Database=DD_ECM;User Id=sa;Password=123456789dD!"

        Dim oConfigData As Config = New Config() With {
            .Debug = False,
            .GDPictureVersion = "11.2024",
            .UseWindream = False,
            .ConnectionString = connectionString
        }

        Dim Worker As ExtractAttachmentsFromEMLFile = New ExtractAttachmentsFromEMLFile()

        ' FileOpen Dialog
        Dim fileOpenDlg = OpenFileDialog2

        If fileOpenDlg.ShowDialog() = DialogResult.OK Then
            Dim oFilename = fileOpenDlg.FileName

            ' Call Extract Method
            Worker.CallWorkerProcess(oFilename, oConfigData)
        End If

    End Sub
End Class
