Imports System.IO
Imports Independentsoft
Imports System.Text.RegularExpressions

Public Class ClassFilehandle
    ''' <summary>
    ''' Diese Funktion entfernt alle Zeichen aus dem übergebenen String
    ''' die in Dateinamen nicht erlaubt sind.
    ''' </summary>
    ''' <param name="Input">Der zu prüfende String</param>
    ''' <returns>String ohne nichterlaubte Zeichen</returns>
    Public Shared Function InvalidCharacters(Input As String) As String
        Dim replacement = ""
        'Return System.Text.RegularExpressions.Regex.Replace(Input, "[\\/:*?""<>|\r\n]", "", System.Text.RegularExpressions.RegexOptions.Singleline)
        Dim regexSearch = New String(Path.GetInvalidFileNameChars()) & New String(Path.GetInvalidPathChars())
        Dim r = New Regex(String.Format("[{0}]", Regex.Escape(regexSearch)))
        Return r.Replace(Input, replacement)
    End Function
    Public Shared Function Decide_FileHandle(filename As String, handletype As String)
        Try
            If filename.EndsWith(".msg") Then
                CURRENT_MESSAGEID = ""
                Dim _msg As New Msg.Message(filename)
                If _msg.Attachments.Count > 0 Then
                    Dim result As MsgBoxResult

                    If USER_LANGUAGE = "de-DE" Then
                        result = MessageBox.Show("Achtung: Die Email enthält Anhänge!" & vbNewLine & "Wollen Sie die Anhänge separat indexieren und herauslösen?", "Nachfrage zur Indexierung:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    Else
                        result = MessageBox.Show("Attention: This Email contains Attachments!" & vbNewLine & "Do you want to extract the attachments and index them seperately?", "Question about Indexing:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    End If

                    If result = MsgBoxResult.Yes Then
                        If handletype.StartsWith("|FW") Then
                            Return Email_Decay(filename, True)
                        Else
                            Return Email_Decay(filename)
                        End If
                    End If
                End If
            End If
            Return Insert_GI_File(filename, handletype)
        Catch ex As Exception
            MsgBox("Unexpected Error in Decide_FileHandle: " & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
    End Function
    Private Shared Function Email_Decay(msgname As String, Optional FW As Boolean = False)
        Try
            Dim msgonly As String = "|MSGONLY|"
            Dim ATT_EXTR As String = "|ATTMNTEXTRACTED|"
            If FW = True Then
                msgonly = "|FW_MSGONLY|"
                ATT_EXTR = "|FW_ATTMNTEXTRACTED|"
            End If
            Dim erfolgreich As Boolean = False
            Dim msg As New Msg.Message(msgname)

            If Not msg.InternetMessageId Is Nothing Then
                CURRENT_MESSAGEID = msg.InternetMessageId
            Else
                If LogErrorsOnly = False Then ClassLogger.Add(">> Email_Decay: Es konnte keine Message-ID gelesen werden. Eine GUID wird erzeugt!", False)
                Dim sGUID As String
                sGUID = System.Guid.NewGuid.ToString()
                CURRENT_MESSAGEID = sGUID
            End If

            'Nur die MSGDatei ablegen
            Dim tempfile As String = Path.Combine(Path.GetTempPath, Path.GetFileNameWithoutExtension(msgname) & "_excl_att.msg")
        
            If File.Exists(tempfile) Then
                File.Delete(tempfile)
            End If
            Dim _msgEXAtt As New Msg.Message(msgname)
            _msgEXAtt.Attachments.Clear()
            _msgEXAtt.Save(tempfile)
            'Datei in Array zum Templöschen speichern
            TEMP_FILES.Add(tempfile)

            If Insert_GI_File(tempfile, msgonly) = True Then
                erfolgreich = True
                'Hier nun die Anhänge herauslösen
                Dim _msg As New Msg.Message(msgname)
                Dim i1 As Integer = 1

                If LogErrorsOnly = False Then ClassLogger.Add(">> Anzahl der Attachments: " & _msg.Attachments.Count, False)
                For Each attachment As Independentsoft.Msg.Attachment In _msg.Attachments
                    If erfolgreich = False Then
                        Exit For
                    End If
                    Dim attachment_name As String
                    If attachment.LongFileName Is Nothing Then
                        attachment_name = attachment.DisplayName
                    Else
                        attachment_name = attachment.LongFileName
                    End If
                    If Not attachment_name.Contains("inline") Then
                        'Sonderzeichen entfernen
                        attachment_name = ClassFilehandle.InvalidCharacters(attachment_name)
                        tempfile = Path.Combine(Path.GetTempPath, attachment_name)
                        tempfile = ClassFilehandle.Versionierung_Datei(tempfile)
                        If tempfile <> "" Then
                            attachment.Save(tempfile)
                            'Datei in Array zum Templöschen speichern
                            TEMP_FILES.Add(tempfile)
                            If LogErrorsOnly = False Then ClassLogger.Add(">> Attachment (" & i1 & "):" & tempfile, False)
                            'nun der Insert des Anhanges
                            erfolgreich = Insert_GI_File(tempfile, ATT_EXTR)
                            i1 += 1
                        End If
                    End If
                Next
            End If
            Return erfolgreich
        Catch ex As Exception
            MsgBox("Error in Email_Decay: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Function

    Private Shared Function Insert_GI_File(filename As String, handleType As String)
        Try
            filename = filename.Replace("'", "''")

            Dim filename_only As String = Path.GetFileName(filename)
            Dim ins As String = "INSERT INTO TBGI_FILES_USER (FILENAME2WORK, USER@WORK,HANDLE_TYPE,FILENAME_ONLY) VALUES ('" & filename & "','" & Environment.UserName & "','" & handleType & "','" & filename_only & "')"
            Return ClassDatabase.Execute_non_Query(ins, True)

        Catch ex As Exception
            Return False
        End Try
    End Function
    Public Shared Function IsFileInUse(ByVal fullFilePath As String) As Boolean
        ' Gibt zurück, ob die übergebene Datei momentan exklusiv zu haben ist.
        ' Prüft, ob die angegeben Datei aktuell durch eine
        ' andere Anwendung in Benutzung ist
        Dim ff As Integer = FreeFile()
        If System.IO.File.Exists(fullFilePath) Then
            Try
                ' Versuchen, die Datei mit *exklusiven* Lese- und
                ' Schreibrechten zu öffnen
                FileOpen(ff, fullFilePath, OpenMode.Binary, OpenAccess.ReadWrite, OpenShare.LockReadWrite)
            Catch ex As Exception
                ' Ist ein Fehler aufgetreten, so wird nach außen hin generell
                ' davon ausgegangen, dass die Datei in Benutzung ist (obwohl
                ' auch andere Ursachen, etwa Rechteprobleme, möglich sind).
                If LogErrorsOnly = False Then ClassLogger.Add(">> FileInUse Message: " & ex.Message, False)
                IsFileInUse = True
            Finally
                ' Die eventuell geöffnete Datei schließen
                FileClose(ff)
            End Try
            Return False
        End If

    End Function
    Public Shared Function Versionierung_Datei(Dateiname As String)
        Dim extension
        Dim _NewFileString
        Try
            Dim version As Integer = 1

            Dim Stammname As String = Path.GetDirectoryName(Dateiname) & "\" & Path.GetFileNameWithoutExtension(Dateiname)
            extension = Path.GetExtension(Dateiname)

            Dim _neuername As String = Stammname
            'Dim MoveFilename As String = DATEINAME.Replace(element.Value, "")
            'Überprüfen ob File existiert
            If File.Exists(_neuername & extension) = False Then
                _NewFileString = _neuername
            Else
                Do While File.Exists(_neuername & extension)
                    version = version + 1
                    _neuername = Stammname & "~" & version
                    _NewFileString = _neuername
                Loop
            End If
            Return _NewFileString & extension
        Catch ex As Exception
            ClassLogger.Add(" - Error in versioning file - error: " & vbNewLine & ex.Message)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in versioning file:")
            Return ""
        End Try

    End Function
    '' <summary>
    ''' Ersetzt alle nicht zulässigen Zeichen im angegebenen Dateinamen
    ''' </summary>
    ''' <param name="sFilename">Dateiname ohne Pfadangabe</param>
    ''' <param name="sChar">Ersatzzeichen für alle unzulässigen Zeichen 
    ''' im Dateinamen</param>
    Public Shared Function CleanFilename(ByVal sFilename As String, Optional ByVal REPLACEChar As String = "") As String
        If LogErrorsOnly = False Then ClassLogger.Add(" >> Filename before CleanFilename: '" & sFilename & "'", False)
        If sFilename.Contains(".\") Then
            sFilename = sFilename.Replace(".\", "\")
        End If
        'If sFilename.Contains("'") Then
        '    sFilename = sFilename.Replace("'", "")
        'End If
        'If sFilename.Contains("..") Then
        '    sFilename = sFilename.Replace("..", ".")
        'End If
        ' alle nicht zulässigen Zeichen ersetzen
        sFilename = System.Text.RegularExpressions.Regex.Replace(sFilename, REGEX_CLEAN_FILENAME, REPLACEChar)
        sFilename = System.Text.RegularExpressions.Regex.Replace(sFilename, "[\\/:*?""<>|\r\n]", "", System.Text.RegularExpressions.RegexOptions.Singleline)
        'Dim oCleanFileName As String = String.Join(REPLACEChar, sFilename.Split(Path.GetInvalidFileNameChars()))
        Dim oCleanFileName As New System.IO.FileInfo(System.Text.RegularExpressions.Regex.Replace(sFilename, String.Format("[{0}]", String.Join(String.Empty, Path.GetInvalidFileNameChars)), REPLACEChar))
        If LogErrorsOnly = False Then ClassLogger.Add(" >> Filename after CleanFilename: '" & sFilename & "'", False)
        Return sFilename
    End Function
End Class
