Option Explicit On

Imports System.Text.RegularExpressions
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Base
Imports DigitalData.Modules.Language
Imports DigitalData.Modules.Filesystem
Imports DigitalData.Modules.Messaging
Imports Limilabs.Mail
Imports DigitalData.GUIs.Common

Public Class ClassFilehandle
    Inherits BaseClass

    Private ReadOnly FileEx As File
    Private ReadOnly Email As Email2
    Private ReadOnly UserFiles As ClassUserFiles
    Private ReadOnly TempFiles As New List(Of String)

    Public Sub New(pLogConfig As LogConfig)
        MyBase.New(pLogConfig)
        Email = New Email2(pLogConfig)
        FileEx = New File(pLogConfig)
        UserFiles = New ClassUserFiles(pLogConfig)
    End Sub

    Public Sub ClearTempFiles()
        For Each oFile In TempFiles
            Try
                IO.File.Delete(oFile)
                Logger.Debug("Temp file [{0}] was deleted.", oFile)
            Catch ex As Exception
                Logger.Warn("Temp file [{0}] could not be deleted", oFile)
                Logger.Error(ex)
            End Try
        Next
        Email.Clear_TempFiles()
        TempFiles.Clear()
    End Sub

    Public Function CheckDuplicateFiles(Filepath As String, ModuleTitle As String)
        Dim oFileInfo As New IO.FileInfo(Filepath)
        Dim oFilename As String = oFileInfo.Name
        Dim oFileExists As Date = UserFiles.FileExistsinDropTable(Filepath)

        If oFileExists.Equals(Date.MinValue) Then
            Return True
        Else
            'Dim oResult As DialogResult
            Dim oDate As String = oFileExists.ToString("d")
            ' Dim oBoxTitle = $"GLOBIX - {ModuleTitle}"

            Dim ofrmDuplicate As New frmFileflow_Duplicate(oFilename, oDate)

            'Dim oBoxOptions = MsgBoxStyle.Question Or MsgBoxStyle.YesNo
            ofrmDuplicate.ShowDialog()

            If ofrmDuplicate.DialogResult = DialogResult.Yes Then
                Return True
            End If
        End If

        Return False
    End Function

    Public Function Decide_FileHandle(pFilepath As String, pHandletype As String) As Boolean
        Try
            Dim oTempFilePath = pFilepath

            Dim oInboxRegex As New Regex("\.INBOX\d+$")

            If oInboxRegex.IsMatch(oTempFilePath) Then
                Logger.Info("Renaming INBOX file to EML")

                Try
                    Dim oInfo As New IO.FileInfo(oTempFilePath)
                    Logger.Info("Old Name: {0}", oInfo.Name)
                    Dim oNewName = $"{oInfo.Name}.eml"
                    Logger.Info("New Name: {0}", oNewName)
                    Dim oTempDirectory = IO.Path.GetTempPath()
                    Dim oNewPath = IO.Path.Combine(oTempDirectory, oNewName)

                    IO.File.Copy(oInfo.FullName, oNewPath)

                    TempFiles.Add(oNewPath)

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

            If oTempFilePath.ToUpper.EndsWith(".MSG") Or oTempFilePath.ToUpper.EndsWith(".EML") Then
                My.Application.Globix.CurrMessageID = ""
                Dim oMail As IMail = Email.Load_Email(oTempFilePath)
                If oMail.Attachments.Count > 0 Then
                    Dim oTitle As String
                    Dim oMessage As String

                    If My.Application.User.Language = "de-DE" Then
                        oTitle = "Nachfrage zur Indexierung:"
                        oMessage = "Achtung: Die Email enthält Anhänge!" & vbNewLine & "Wollen Sie die Anhänge separat indexieren und herauslösen?"
                    Else
                        oTitle = "Question about Indexing:"
                        oMessage = "Attention: This Email contains Attachments!" & vbNewLine & "Do you want to extract the attachments and index them seperately?"
                    End If
                    Dim oResult As DialogResult

                    ' Weird hack to force messagebox to be topmost
                    ' https://stackoverflow.com/questions/1220882/keep-messagebox-show-on-top-of-other-application-using-c-sharp
                    oResult = MessageBox.Show(oMessage, oTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly)


                    If oResult = MsgBoxResult.Yes Then
                        Dim oIsFolderWatch = pHandletype.StartsWith("|FW")
                        Return Save_EmailAndAttachmentsToDisk(oTempFilePath, oIsFolderWatch)
                    End If
                End If
            End If

            If oTempFilePath.ToUpper.EndsWith(".LNK") Then
                Dim oMSG As String
                If My.Application.User.Language = "de-DE" Then
                    oMSG = "Verknüpfungen können nicht abgelegt werden!"
                Else
                    oMSG = "Shortcuts cannot be droppped!"
                End If
                MsgBox(oMSG, MsgBoxStyle.Information, "Index Load")

                Return False
            End If

            Return UserFiles.Insert_GI_File(oTempFilePath, pHandletype)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Unexpected error in Decide_FileHandle")

            Return False
        End Try
    End Function

    Private Function Save_EmailAndAttachmentsToDisk(pEmailFilePath As String, Optional pFolderWatch As Boolean = False) As Boolean
        Try
            Dim oMessageOnlyMarker As String = "|MSGONLY|"
            Dim oExtractedAttachmentMarker As String = "|ATTMNTEXTRACTED|"
            If pFolderWatch = True Then
                oMessageOnlyMarker = "|FW_MSGONLY|"
                oExtractedAttachmentMarker = "|FW_ATTMNTEXTRACTED|"
            End If
            Dim oSuccess As Boolean = False

            Logger.Info("Converting file to Eml if needed: [{0}]", pEmailFilePath)
            Dim oEmail As IMail = Email.Load_Email(pEmailFilePath)

            If oEmail.MessageID IsNot Nothing Then
                My.Application.Globix.CurrMessageID = oEmail.MessageID
            Else
                Logger.Info("Es konnte keine Message-ID gelesen werden. Eine GUID wird erzeugt!")
                My.Application.Globix.CurrMessageID = Guid.NewGuid.ToString()
            End If

            Dim oEmailFilePathWithoutAttachments = Email.Remove_AttachmentsFromEmail(pEmailFilePath, "_excl_attachments")

            TempFiles.Add(oEmailFilePathWithoutAttachments)

            If UserFiles.Insert_GI_File(oEmailFilePathWithoutAttachments, oMessageOnlyMarker) = True Then
                oSuccess = True

                Dim oAttachments As List(Of String) = Email.Save_AttachmentsToDisk(pEmailFilePath)

                Logger.Debug("Saved [{0}] attachments to disk.", oAttachments.Count)

                For Each oAttachment In oAttachments
                    TempFiles.Add(oAttachment)

                    Logger.Debug("Saved attachment [{0}].", oAttachment)
                    oSuccess = UserFiles.Insert_GI_File(oAttachment, oExtractedAttachmentMarker)

                    If oSuccess = False Then
                        Logger.Warn("Saving attachment to disk failed: [{0}]", oAttachment)
                        Exit For
                    End If
                Next
            End If

            Return oSuccess
        Catch ex As Exception
            Logger.Warn("Saving email to disk failed (Email_Decay)")
            Logger.Error(ex)

            Return False
        End Try
    End Function
End Class
