Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Windream
Imports DigitalData.Modules.Config
Public Class frmMain
    Private _ArgumentLength As Integer

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            Me.Hide()
            Me.Visible = False
            Dim oLogConfig As New LogConfig(LogConfig.PathType.CustomPath,
                                        Application.LocalUserAppDataPath & "\Log",
                                        Nothing,
                                        My.Application.Info.CompanyName,
                                        My.Application.Info.ProductName)

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

            If Connect2Windream(oUserPW) = True Then
                Dim oArguments As String() = Environment.GetCommandLineArgs()
                If ParseArgs(oArguments) = True Then
                    If StreamIndexFile() = True Then
                        oErrorImport = False
                    Else
                        oErrorImport = True
                    End If
                End If
            Else
                oErrorMessage = "Could not initialize windream"
            End If

            txtUser.Text = CONFIG.Config.WMUsername
            Me.txtPW.Text = oUserPW
            txtWMDrive.Text = CONFIG.Config.WMDrive
            txtWMRelpath.Text = CONFIG.Config.WMRelPath
            txtWMServer.Text = CONFIG.Config.WMUserPW
            txtDomain.Text = CONFIG.Config.Domain
            'txtCommands.Text = CONFIG.Config.Arguments
            txtCommands.Text = My.Settings.TestParams
            If oErrorParse = True Then
                MsgBox("Error in Parsing or Indexing!", MsgBoxStyle.Critical)
                Me.Visible = True
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try

    End Sub

    Public Sub InitUserConfig()
        CONFIG = New ConfigManager(Of ClassConfig)(LOGCONFIG, Application.UserAppDataPath, Application.CommonAppDataPath, Application.StartupPath)
        LOGGER.Info("Config loaded")


        'Settings_Load()
    End Sub
    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")
                    bsiWMConnect.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                    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)
        Try
            If pArguments.Length <= 3 Then
                _ArgumentLength = pArguments.Length
                LOGGER.Warn($"Insufficient number of arguments [{pArguments.Length}]!")
                BarStaticinfo.Caption = $"Insufficient number of arguments - {Now.ToString}"
                oErrorMessage = BarStaticinfo.Caption
                BarStaticinfo.ItemAppearance.Normal.BackColor = Color.Red
                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 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@", "")
                    Dim oWMFolder = System.IO.Path.GetDirectoryName(oTargetPath)
                    Dim oWindowsPath = oTargetPath
                    OExtension = IO.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

                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
                    Dim oINDEXInfotemp = oArg
                    oINDEXInfotemp = oINDEXInfotemp.Replace("-index@{", "")
                    oINDEXInfotemp = oINDEXInfotemp.Replace("}", "")
                    Dim oSplit() = oINDEXInfotemp.ToString.Split(";")
                    LOGGER.Debug($" [{oSplit.Length}] Indices transmitted...")
                    oIndexArr = oSplit

                End If
                ocount += 1
            Next
            Return True
        Catch ex As Exception
            LOGGER.Warn("Error in ParseArgs:" & vbNewLine & ex.Message)
            oErrorMessage &= vbNewLine & "Error in ParseArgs:" & vbNewLine & ex.Message
            oErrorParse = True
            BarStaticinfo.Caption = $"Error in ParseArgs - {Now.ToString}"
            BarStaticinfo.ItemAppearance.Normal.BackColor = Color.Red
            Return False
        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
    Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        If oErrorImport = False Then
            Me.Close()
        End If
        If oErrorParse = True And _ArgumentLength <> 1 Then
            MsgBox("A unexpected error occured while Parsing arguments!" & vbNewLine & oErrorMessage, MsgBoxStyle.Critical)
            Process.Start(LOGCONFIG.LogDirectory)

        End If
        If oErrorImport = True Then
            MsgBox("A unexpected error occured while initializing!" & vbNewLine & oErrorMessage, MsgBoxStyle.Critical)
        End If
    End Sub





    Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
        Dim wrapper As New ClassEncryption("!35452didalog=")
        Dim cipherText As String = wrapper.EncryptData(Me.txtPW.Text)
        Dim pw As String = cipherText
        CONFIG.Config.WMUserPW = pw

        CONFIG.Config.WMUsername = txtUser.Text
        CONFIG.Config.WMDrive = txtWMDrive.Text
        CONFIG.Config.WMRelPath = txtWMRelpath.Text
        CONFIG.Config.WMServer = txtWMServer.Text
        CONFIG.Config.Domain = txtDomain.Text
        CONFIG.Save()
        BarStaticinfo.Caption = $"WM-Settings saved - {Now.ToString}"
        BarStaticinfo.ItemAppearance.Normal.BackColor = Color.Lime
    End Sub

    Private Sub BarButtonItem2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem2.ItemClick

        WINDREAM = New Windream(LOGCONFIG, False, txtWMDrive.Text, txtWMRelpath.Text, True, txtWMServer.Text, txtUser.Text, txtPW.Text, txtDomain.Text)
        If Not IsNothing(WINDREAM) Then
            MsgBox("Windream-Connext successfull!", MsgBoxStyle.Information)
        End If
    End Sub

    Private Sub GroupBox1_Enter(sender As Object, e As EventArgs) Handles GroupBox1.Enter
        RibbonPageGroup1.Enabled = True
    End Sub

    Private Sub GroupBox1_Leave(sender As Object, e As EventArgs) Handles GroupBox1.Leave
        RibbonPageGroup1.Enabled = False
    End Sub
    Private Sub BarButtonItem4_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem4.ItemClick
        Process.Start(LOGCONFIG.LogDirectory)
    End Sub

    Private Sub BarButtonItem5_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem5.ItemClick
        My.Settings.TestParams = txtCommands.Text
        My.Settings.Save()
        'CONFIG.Config.Arguments = txtCommands.Text
        'CONFIG.Save()
        Dim oArgs() As String = txtCommands.Text.Split("|")
        LOGGER.Debug($"[{oArgs.Length}] Arguments will be checked...")
        If IsNothing(WINDREAM) Then
            Dim oUserPW = GetUserPWPlain()

            If Connect2Windream(oUserPW) = False Then
                MsgBox("Windream could not be initialized!! Check Your log!", MsgBoxStyle.Critical)
                Exit Sub
            End If
        End If
        If ParseArgs(oArgs) = False Then
            MsgBox("An unexpected error occured while parsing arguments. Check the log!", MsgBoxStyle.Critical)
            Process.Start(LOGCONFIG.LogDirectory)
        Else
            If StreamIndexFile() = True Then
                MsgBox("Import succeeded!", MsgBoxStyle.Information)
            Else
                MsgBox("Unexpected Error while streaming or indexing WMFile! Check the logfile!", MsgBoxStyle.Critical)
                Process.Start(LOGCONFIG.LogDirectory)
            End If
        End If

    End Sub
    Public Function StreamIndexFile()
        Try
            'Checks and creates the path if necessary
            WINDREAM.NewFolder(oTargetPath, oExtension)
            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
                LOGGER.Info($"File successfully streamed to windream [{oTargetPath}]! Now indexing...")
                For Each oIndex2 As String In oIndexArr
                    Dim oIndexInfo() = oIndex2.Split("=")
                    Dim oIndexName = oIndexInfo(0)
                    Dim oIndexvalue = oIndexInfo(1)
                    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

                Next
                If oResult = True Then
                    LOGGER.Info("Import finished!")
                    oErrorImport = False
                End If
            End If
            Return oResult
        Catch ex As Exception
            LOGGER.Warn($"Error while indexing: {ex.Message}")
        End Try

    End Function

    Private Sub txtCommands_GotFocus(sender As Object, e As EventArgs) Handles txtCommands.GotFocus
        RibbonPageGroup3.Enabled = True
    End Sub

    Private Sub txtCommands_LostFocus(sender As Object, e As EventArgs) Handles txtCommands.LostFocus
        RibbonPageGroup3.Enabled = False
    End Sub

    Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub GroupBox2_Enter(sender As Object, e As EventArgs) Handles GroupBox2.Enter
        RibbonPageGroup3.Enabled = False
    End Sub
End Class
