Imports System
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Windream
Imports DigitalData.Modules.Config
Imports System.IO
Imports System.Text.RegularExpressions
Imports DigitalData.Modules.Database

Module Module1
    Private _ArgumentLength As Integer
    Public _database As MSSQLServer
    Public oRegExArg As String
    Public Function Main(args As String()) As Integer
        Dim oReturnResult As Integer
        Try

            oReturnResult = 0
            ' Console.WriteLine("Starting up WIDig...")
            Dim opath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
            Dim oLogConfig As New LogConfig(LogConfig.PathType.AppData, Nothing, Nothing,
                                          "Digital Data",
                                          "WIDigCons")

            LOGCONFIG = oLogConfig
            LOGGER = LOGCONFIG.GetLogger
            InitUserConfig()
            LOGCONFIG.Debug = CONFIG.Config.LOG_DEBUG
            LOGGER = LOGCONFIG.GetLogger
            Dim oUserPW = GetUserPWPlain()
            LOGGER.Debug("Initializing MainForm....")

            System.Console.WriteLine($"Starting up WIDig...")
            If Connect2Windream(oUserPW) = True Then
                System.Console.WriteLine($"Windream initialized!")
                If InitDatabase() = True Then
                    Load_DB_DAta()
                    'Dim oArguments As String() = Environment.GetCommandLineArgs()
                    If ParseArgs(args) = True Then
                        System.Console.WriteLine($"Parsed all arguments!")
                        If StreamORIndexFile() = True Then
                            oErrorImport = False
                            oReturnResult = 1
                        Else
                            System.Console.WriteLine($"###Error in StreamIndexFile!####")
                            oErrorImport = True
                        End If
                    Else
                        System.Console.WriteLine($"###Error in ParseArgs!####")
                        System.Console.WriteLine($"### Error in ParseArgs ####")
                        System.Console.WriteLine(oErrorMessage)
                        System.Console.WriteLine("### For more information check the log! Press any key to exit! ####")
                        System.Console.WriteLine($"####################")
                        Console.ReadKey()
                    End If


                Else
                    oErrorMessage = "Could not initialize DB"
                End If

            Else
                oErrorMessage = "Could not initialize windream"

            End If


            If oErrorParse = True Or oErrorImport = True Then
                System.Console.WriteLine(oErrorMessage)
                System.Console.WriteLine("### For more information check the log! Press any key to exit! ####")
                System.Console.WriteLine($"####################")
                Console.ReadKey()
                oReturnResult = 0

            Else
                oReturnResult = 1
            End If
            Return oReturnResult
        Catch ex As Exception
            LOGGER.Error(ex)
            Return oReturnResult
        End Try

    End Function
    Public Sub InitUserConfig()
        Dim oUserAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
        oUserAppDataPath = oUserAppDataPath & "\Digital Data\WIDigDat"
        Dim oCommonAppDataPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
        CONFIG = New ConfigManager(Of ClassConfig)(LOGCONFIG, oUserAppDataPath, System.AppDomain.CurrentDomain.BaseDirectory, oCommonAppDataPath)
        System.Console.WriteLine($"Config loaded!")
        LOGGER.Info("Config loaded")
        'Settings_Load()
    End Sub
    Public Function InitDatabase() As Boolean
        If My.Settings.MyECM_ConnectionString = String.Empty Then
            Return False
        End If

        Try
            _database = New MSSQLServer(LOGCONFIG, My.Settings.MyECM_ConnectionString)
            If _database.DBInitialized = True Then
                Return True
            Else
                Return False
            End If

        Catch ex As Exception
            LOGGER.Error(ex)
            Return False
        End Try
    End Function

    Public Function Load_DB_DAta()
        Try
            Dim oSql = "SELECT [REGEX] FROM [TBDD_FUNCTION_REGEX] WHERE FUNCTION_NAME = 'WM-INDEXER-INDEX_GROUP'"
            oRegExArg = _database.GetScalarValue(oSql, 120)
            If oRegExArg.Length = 0 Then
                oRegExArg = 0
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
            Return False
        End Try
    End Function
    Private Function Connect2Windream(oPW As String)
        Try
            WINDREAM = New Windream(LOGCONFIG, False, CONFIG.Config.WMDrive, CONFIG.Config.WMRelPath, True, CONFIG.Config.WMServer, CONFIG.Config.WMUsername, oPW, CONFIG.Config.Domain)
            If Not IsNothing(WINDREAM) Then
                If WINDREAM.SessionLoggedin = True Then
                    LOGGER.Debug("windream initialisiert")
                    Return True
                End If
            End If
        Catch ex As Exception
            LOGGER.Warn("CHECKING WMConnectivity: " & ex.Message)
            Return False
        End Try
    End Function
    Private Function GetUserPWPlain()
        Try
            Dim PWplainText As String
            Dim wrapper As New ClassEncryption("!35452didalog=")
            If CONFIG.Config.WMUserPW = String.Empty Then
                PWplainText = ""
            Else
                PWplainText = wrapper.DecryptData(CONFIG.Config.WMUserPW)
            End If

            Return PWplainText
        Catch ex As Exception
            LOGGER.Warn("Error in GetUserPWPlain - the password [" & CONFIG.Config.WMUserPW & "] could not be decrypted", False)
            Return String.Empty
        End Try
    End Function
    Public Function ParseArgs(pArguments As String(), Optional pTest As Boolean = False)
        Dim oINDEXInfoStarted As Boolean = False
        Dim oINDEXInfotemp As String = ""
        Try
            If pArguments.Length <= 3 Then
                _ArgumentLength = pArguments.Length
                LOGGER.Warn($"Insufficient number of arguments [{pArguments.Length}]!")
                System.Console.WriteLine($"Insufficient number of arguments - {Now.ToString}")
                oErrorParse = True
                Return False
            End If

            Dim ocount As Integer = 0
            For Each oArg As String In pArguments
                LOGGER.Debug($"[{ocount}] {oArg}")
                oArg = oArg.Replace("""", "")
                If oArg.StartsWith("-Source@") Then
                    oSourceFile = oArg.Replace("-Source@", "")
                    If IsNumeric(oSourceFile) Then
                        LOGGER.Info($"SourceFile seems to be a DocID [{oSourceFile}]")
                        Dim oSQL = $"SELECT [dbo].[FNDD_GET_WINDREAM_FILE_PATH] ({oSourceFile})"
                        oSourceFile = _database.GetScalarValue(oSQL)
                    End If
                    If System.IO.File.Exists(oSourceFile) = False Then
                        LOGGER.Warn($"Parser@Sourcefile - File [{oSourceFile}] is not existing!")
                        oErrorMessage &= vbNewLine & $"Parser@Sourcefile - File [{oSourceFile}] is not existing!"
                        oErrorParse = True
                        Return False
                    End If

                ElseIf oArg.StartsWith("-Mode@") Then
                    oMode = oArg.Replace("-Mode@", "").ToUpper

                ElseIf oArg.StartsWith("-Target@") Then
                    oTargetPath = oArg.Replace("-Target@", "")
                    If IsNumeric(oTargetPath) Then
                        LOGGER.Info($"Target seems to be a DocID [{oTargetPath}]")
                        Dim oSQL = $"SELECT [dbo].[FNDD_GET_WINDREAM_FILE_PATH] ({oTargetPath})"
                        oSourceFile = _database.GetScalarValue(oSQL)
                    End If
                    Dim oWMFolder = System.IO.Path.GetDirectoryName(oTargetPath)
                    Dim oWindowsPath = oTargetPath
                    oExtension = Path.GetExtension(oWindowsPath)
                    Dim oNormalizePath = WINDREAM.GetNormalizedPath(oTargetPath)
                    If WINDREAM.TestFileExists(oTargetPath) = False Then
                        LOGGER.Info($"WMFile [{oTargetPath}] not existing!")
                    End If
                    If oMode = "IMPV" Then
                        Dim oWMCheckPath = WINDREAM.VersionWMFilename(oTargetPath, System.IO.Path.GetExtension(oTargetPath))
                        If oNormalizePath.ToUpper <> oWMCheckPath.ToString.ToUpper Then
                            LOGGER.Info($"Target [{oNormalizePath}] already existed!! - NewWMFilename [{oWMCheckPath}]")
                            oTargetPath = oWMCheckPath
                        End If
                    End If
                    'Checks and creates the path if necessary
                    WINDREAM.NewFolder(oTargetPath, oExtension)

                ElseIf oArg.StartsWith("-WMOT@") Then
                    oWMObjecttype = oArg.Replace("-WMOT@", "")
                    Dim oexists As Boolean = False
                    Dim myWMOTypes = WINDREAM.ObjectTypes
                    For Each otype As String In myWMOTypes
                        If oWMObjecttype = otype Then
                            oexists = True
                            Exit For
                        End If
                    Next
                    If oexists = False Then
                        LOGGER.Info($"WMObjekttype [{oWMObjecttype}] not existing!!")
                        oErrorMessage &= vbNewLine & $"WMObjekttype [{oWMObjecttype}] not existing!!"
                        Return False
                        oErrorParse = True
                    Else
                        WMIndices = WINDREAM.GetIndiciesByObjecttype(oWMObjecttype)
                    End If
                ElseIf oArg.StartsWith("-index@") Then
                    oINDEXInfotemp = oArg
                    oINDEXInfoStarted = True
                    oINDEXInfotemp = oINDEXInfotemp.Replace("-index@", "")

                Else
                    If oINDEXInfoStarted Then
                        oINDEXInfotemp &= " " & oArg
                    End If
                End If
                ocount += 1
            Next

            Dim oIndexparts As String() = oINDEXInfotemp.Split(New String() {"#~#"}, StringSplitOptions.RemoveEmptyEntries)

            LOGGER.Info($" [{oIndexparts.Length}] Indices transmitted...")
            oIndexArr = oIndexparts
            Return True
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Warn("Error in ParseArgs:" & vbNewLine & ex.Message)
            oErrorMessage &= vbNewLine & "Error in ParseArgs:" & vbNewLine & ex.Message
            oErrorParse = True
            System.Console.WriteLine($"Error in ParseArgs - {Now.ToString}")

            Return False
        End Try
    End Function
    Public Function StreamORIndexFile()
        Try
            Dim oResult As Boolean = False
            If oMode = "IMPV" Then
                oResult = WINDREAM.NewFileStream(oSourceFile, oTargetPath)
            ElseIf oMode = "IMPO" Then
                Dim oDeleted = WINDREAM.RemoveFile(oTargetPath)
                If oDeleted = True Then
                    oResult = WINDREAM.NewFileStream(oSourceFile, oTargetPath)
                Else
                    LOGGER.Warn($"Mode ImportOverwrite is active - but WMFile could not be deleted!!")
                End If
            ElseIf oMode = "NI" Then
                oResult = True
            End If


            If oResult = True Then
                If oMode <> "NI" Then
                    LOGGER.Info($"File successfully streamed to windream [{oTargetPath}]! Now indexing...")
                End If

                For Each oIndex2 As String In oIndexArr
                    Dim oIndexInfo() = oIndex2.Split("={")
                    Dim oIndexName = oIndexInfo(0)
                    Dim oIndexvalue
                    Dim r As Regex = New Regex(oRegExArg, RegexOptions.IgnoreCase)
                    '    ' Match the regular expression pattern against a text string.
                    Dim m As Match = r.Match(oIndex2)
                    Do While m.Success

                        '        oClearedBodyText = oClearedBodyText.Replace(m.Value, "")
                        'Dim g As Group = m.Groups(1)
                        Dim g1 As Group = m.Groups(2)
                        Dim g2 As Group = m.Groups(3)

                        If Not IsNothing(g2.Value) Then
                            oIndexvalue = g2.Value
                            Console.WriteLine($"Indexvalue: {oIndexvalue}")
                        End If
                        If Len(oIndexvalue) > 0 Then
                            If WMIndex_exists(oIndexName) = True Then
                                LOGGER.Info($"Setting Index: oIndexName [{oIndexName}] - oIndexvalue [{oIndexvalue}]")
                                If WINDREAM.SetFileIndex(oTargetPath, oIndexName, oIndexvalue, oWMObjecttype) = False Then
                                    LOGGER.Info($"Index could not be set...")
                                    If WINDREAM.RemoveFile(oTargetPath) = True Then
                                        LOGGER.Info($"File deleted after error!")
                                    End If
                                    oResult = False
                                    Exit For
                                End If
                            Else
                                LOGGER.Warn($"Transmitted index with name [{oIndexName}] is not existing in WM Objecttype!")
                                If WINDREAM.RemoveFile(oTargetPath) = True Then
                                    LOGGER.Info($"File deleted after error!")
                                End If
                                oResult = False
                                Exit For
                            End If
                        End If
                        m = m.NextMatch()
                    Loop
                Next
                If oResult = True Then
                    LOGGER.Info("## All Tasks finished ##")
                    oErrorImport = False
                End If
            End If
            Return oResult
        Catch ex As Exception
            LOGGER.Warn($"Unexpected Error in StreamORIndexFile: {ex.Message}")
            LOGGER.Error(ex)
        End Try

    End Function
    Private Function WMIndex_exists(pIndex As String)
        Dim oexist As Boolean = False
        For Each oWMIndex As String In WMIndices
            If oWMIndex = pIndex Then
                Return True
            End If
        Next
        Return oexist
    End Function

End Module
