Imports DigitalData.Modules.Base
Imports DigitalData.Modules.Filesystem
Imports DigitalData.Modules.Logging
Imports System.IO
Imports File = DigitalData.Modules.Filesystem.File

Public Class ClassUserFiles
    Inherits BaseClass
    Private Property FILESYSTEM As File
    Public Sub New(pLogConfig As LogConfig)
        MyBase.New(pLogConfig)
        FILESYSTEM = New File(pLogConfig)
    End Sub

    Public Function Insert_GI_File(filename As String, handleType As String) As Boolean
        Try
            filename = filename.Replace("'", "''")

            Dim oHash As String = String.Empty

            If IO.File.Exists(filename) Then
                If (filename.ToUpper.EndsWith(".MSG") Or filename.ToUpper.EndsWith(".EML")) And (handleType = "|OUTLOOK_MESSAGE|" Or handleType = "|MSGONLY|") Then
                    oHash = FILESYSTEM.GetChecksumFromString(filename)
                Else
                    oHash = FILESYSTEM.GetChecksum(filename)
                End If
            End If

            Dim filename_only As String = Path.GetFileName(filename)
            Dim ins As String = $"INSERT INTO TBGI_FILES_USER (FILENAME2WORK, USER@WORK, HANDLE_TYPE, FILENAME_ONLY, FILE_HASH) VALUES ('{filename}','{Environment.UserName}','{handleType}','{filename_only}', '{oHash}')"
            Return My.DatabaseECM.ExecuteNonQuery(ins)

        Catch ex As Exception
            Return False
        End Try
    End Function

    Public Function FileExistsinDropTable(Filename As String) As Date
        Dim oSQL As String
        Dim oHash As String
        Dim oFilesystem As New DigitalData.Modules.Filesystem.File(My.LogConfig)

        Try
            My.Application.Globix.DOCUMENT_ID = 0
            If Filename.Contains("'") Then
                Filename = Filename.Replace("'", "''")
            End If

            Try
                oHash = oFilesystem.GetChecksum(Filename)
            Catch ex As Exception
                oHash = ""
            End Try

            oSQL = $"SELECT A.* FROM TBIDB_FILE_OBJECT A INNER JOIN TBIDB_OBJECT B ON A.IDB_OBJ_ID = B.IDB_OBJ_ID
                    WHERE A.FILE_HASH = '{oHash}' AND B.DELETED = 0 ORDER BY A.ADDED_WHEN"
            Dim oResult As DataTable = My.DatabaseIDB.GetDatatable(oSQL)

            If oResult.Rows.Count = 0 Then
                Return Nothing
            Else
                Dim oFirstRow As DataRow = oResult.Rows.Item(0)
                My.Application.Globix.DOCUMENT_ID = oFirstRow.Item("IDB_OBJ_ID")
                Return oFirstRow.Item("ADDED_WHEN")
            End If
        Catch ex As Exception
            MsgBox("Error in FileExistsinDropTable - Error-Message:" & vbNewLine & ex.Message & vbNewLine & "SQL-Command:" & vbNewLine & oSQL, MsgBoxStyle.Critical)
            Return Nothing
        End Try
    End Function
End Class
