Option Explicit On

Imports System.IO
Imports System.Text.RegularExpressions
Imports DevExpress.XtraEditors.Controls
Imports DigitalData.Controls.LookupGrid
Imports DigitalData.GUIs.GlobalIndexer
Imports DigitalData.GUIs.ZooFlow.Globix.Models
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.EDMI.API
Imports DigitalData.Modules.EDMI.API.EDMIServiceReference
Imports DigitalData.Modules.EDMI.API.Constants.DatabaseType
Imports DigitalData.Modules.Language
Imports DigitalData.Modules.Language.Utils
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Patterns
Imports DevExpress.XtraEditors
Imports DevExpress.XtraSplashScreen
Imports DigitalData.GUIs.Common
Public Class frmGlobix_Index
#Region "+++++ Variablen ++++++"
    Private ReadOnly LogConfig As LogConfig
    Private ReadOnly Logger As Logger

    Private Property CancelAttempts As Integer = 0

    Private Const MAX_CANCEL_ATTEMPTS = 2
    Private Const TEXT_MISSING_INPUT = "Bitte vervollständigen Sie die Eingaben!"

    Private Property MultifileCount As Integer
    Public Property FormLoaded As Boolean = False
    Public Property DropType As String


    Public Property ManualIndexes As List(Of ManualIndex)
    Public Property DocTypes As List(Of DocType)
    Public Property SelectedDocType As DocType

    Private Property WindowLocation As ClassWindowLayout
    Private Property Database As DatabaseWithFallback
    Private Property Patterns2 As Patterns2
    Private ReadOnly FormHelper As FormHelper

    Private Property OverlayHandle As IOverlaySplashScreenHandle
    Public Property oSuccess As Boolean = False

    'Public Class ControlMeta
    '    Public Property IndexName As String
    '    Public Property IndexType As String
    '    Public Property MultipleValues As Boolean = False
    'End Class

#End Region

    Public Sub New(pLogConfig As LogConfig)
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        Logger = pLogConfig.GetLogger()
        LogConfig = pLogConfig

        Database = New DatabaseWithFallback(pLogConfig, My.Application.Service.Client, My.DatabaseECM, My.DatabaseIDB)
        WindowLocation = New ClassWindowLayout(pLogConfig)
        Patterns2 = New Patterns2(pLogConfig)
        FormHelper = New FormHelper(pLogConfig, Me)

        Localizer.Active = New LookupGridLocalizer()
    End Sub

    Private Sub frmGlobix_Index_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ColorizeInactiveIcon = DevExpress.Utils.DefaultBoolean.True

        ' Abbruchzähler zurücksetzen
        CancelAttempts = 0

        ' Show Loading Overlay
        OverlayHandle = SplashScreenManager.ShowOverlayForm(Me)

        My.Application.Globix.INDEXING_ACTIVE = True
    End Sub

    Private Async Sub frmGlobix_Index_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        Cursor = Cursors.Default

        checkItemTopMost.Checked = My.UIConfig.Globix.TopMost
        TopMost = My.UIConfig.Globix.TopMost
        BringToFront()
        Focus()

        Try
            DocumentViewer1.Init(LogConfig, My.Application.Settings.GdPictureKey)
        Catch ex As Exception
            Logger.Error(ex)
        End Try

        Try
            Refresh_Dokart()
            pnlIndex.Controls.Clear()

            My.Application.Globix.CURRENT_ISATTACHMENT = False
            Dim oSql = $"SELECT HANDLE_TYPE FROM TBGI_FILES_USER WHERE GUID = {My.Application.Globix.CurrentWorkfile.Id}"
            DropType = Await My.Database.GetScalarValueECMAsync(oSql)

            My.Application.Globix.DeleteOriginalFile = My.UIConfig.Globix.DeleteOriginalFile
            SplitContainerControl1.SplitterPosition = My.UIConfig.Globix.SplitterDistanceViewer
            SourceDeleteItem.Enabled = True
            SourceDeleteItem.Checked = My.UIConfig.Globix.DeleteOriginalFile

            If DropType Is Nothing Then
                Logger.Debug("File with Id [{0}] was not found in TBGI_FILES_USER. Exiting.", My.Application.Globix.CurrentWorkfile.Id)
                CancelAttempts = MAX_CANCEL_ATTEMPTS
                Close()
                Exit Sub
            End If

            SetDropType(DropType)


            labelFilePath.Caption = My.Application.Globix.CurrentWorkfile.FilePath
            WindowLocation.LoadFormLocationSize(Me)


            SetFilePreview(My.UIConfig.Globix.FilePreview)


            MultifileCount = Await My.Database.GetScalarValueECMAsync("SELECT COUNT(*) FROM TBGI_FILES_USER WHERE WORKED = 0 AND GUID <> " & My.Application.Globix.CurrentWorkfile.Id & " AND UPPER(USER@WORK) = UPPER('" & Environment.UserName & "')")
            My.Application.Globix.MULTIINDEXING_ACTIVE = False

            If MultifileCount > 0 Then
                If My.Application.User.Language = "de-DE" Then
                    chkMultiindexing.Caption = $"Alle nachfolgenden Dateien (#{MultifileCount}) identisch indexieren"
                Else
                    chkMultiindexing.Caption = "All following files (#{MultifileCount}) will be indexed identically"
                End If

                chkMultiindexing.Checked = False
                chkMultiindexing.Visibility = DevExpress.XtraBars.BarItemVisibility.Always

            Else
                chkMultiindexing.Visibility = DevExpress.XtraBars.BarItemVisibility.Never

            End If
            If My.UIConfig.Globix.DeleteOriginalFile Then
                SourceDeleteItem.Checked = True
            End If
            ' Letzte Auswahl merken überschreibt die automatische selektion
            If My.UIConfig.Globix.ProfilePreselection Then
                checkItemPreselection.Checked = True

                If My.Application.Globix.CURRENT_LASTDOCTYPE <> "" Then
                    Dim oFoundDocType = cmbDocType.Properties.Items.
                        Cast(Of DocType)().
                        Where(Function(dt) dt.Name = My.Application.Globix.CURRENT_LASTDOCTYPE).
                        FirstOrDefault()
                    If oFoundDocType IsNot Nothing Then
                        cmbDocType.SelectedItem = oFoundDocType
                    End If


                End If
            Else
                oSql = "SELECT DISTINCT T1.DOCTYPE as DocType, T.* FROM TBGI_REGEX_DOCTYPE T, VWGI_DOCTYPE_USER T1 WHERE T.DOCTYPE_ID = T1.DOCTYPE_ID"
                Dim oRegexDoctypeTable = Database.GetDatatable("DTTBGI_REGEX_DOCTYPE", oSql, ECM)

                For Each oRoW As DataRow In oRegexDoctypeTable.Rows
                    Dim oOnlyFilename = Path.GetFileName(My.Application.Globix.CurrentWorkfile.FilePath)
                    If Regex.IsMatch(oOnlyFilename, oRoW.Item("Regex")) Then

                        Logger.Debug("There is a match on REGEX_DOCTYPE: [{0}]", oRoW.Item("DOCTYPE"))
                        Logger.Debug("Regex: [{0}], FileName: [{1}]", oRoW.Item("Regex"), oOnlyFilename)
                        Dim oFoundDocType = cmbDocType.Properties.Items.
                            Cast(Of DocType)().
                            Where(Function(dt) dt.Name = My.Application.Globix.CURRENT_LASTDOCTYPE).
                            FirstOrDefault()

                        If oFoundDocType IsNot Nothing Then
                            cmbDocType.SelectedItem = oFoundDocType
                        End If
                        Exit For
                    End If
                Next
            End If


        Catch ex As Exception
            Logger.Warn("Unexpected error DTTBGI_REGEX_DOCTYPE - ErrorMessage: " & vbNewLine & ex.Message)
            Me.Visible = False
            FormHelper.ShowErrorMessage(ex, "Laden des Formulars")
            Me.Visible = True
        Finally
            SplashScreenManager.CloseOverlayForm(OverlayHandle)
            FormLoaded = True
        End Try
    End Sub


    Public Sub SetDropType(pDropType As String)
        If pDropType Is Nothing Then
            Logger.Debug("File with Id [{0}] was not found in TBGI_FILES_USER. Exiting.", My.Application.Globix.CurrentWorkfile.Id)
            CancelAttempts = MAX_CANCEL_ATTEMPTS
            Close()
        Else
            If pDropType.StartsWith("|FW") Then
                ' Eine Datei aus FolderWatch wird IMMER gelöscht, egal wie die Einstellung in der Config lautet
                My.Application.Globix.DeleteOriginalFile = True
                SourceDeleteItem.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
            ElseIf pDropType.Contains("|OUTLOOK_MESSAGE|") Then
                ' Eine (DragDrop)-Outlook Nachricht wird NIE gelöscht, egal wie die Einstellung in der Config lautet
                My.Application.Globix.DeleteOriginalFile = False
                SourceDeleteItem.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
            Else
                SourceDeleteItem.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
            End If

            If pDropType = "|DROPFROMFSYSTEM|" Then
                If My.Application.User.Language <> "de-DE" Then
                    Me.Text = "Storage-Flow of dropped file"
                Else
                    Me.Text = "Ablage-Flow - Dropped File"
                End If
            ElseIf pDropType = "|OUTLOOK_MESSAGE|" Or pDropType = "|FW_MSGONLY|" Then
                Select Case pDropType
                    Case "|FW_MSGONLY|"
                        Logger.Info(".msg-file from folderwatch")
                        If My.Application.User.Language <> "de-DE" Then
                            Me.Text = "Storage-Flow - msg-File (without Attachments) - from Folderwatch"
                        Else
                            Me.Text = "Ablage-Flow - msg-Datei (ohne Anhang) - aus Folderwatch"
                        End If
                    Case "|OUTLOOK_MESSAGE|"
                        Logger.Info(".msg-file through dragdrop")
                        If My.Application.User.Language <> "de-DE" Then
                            Me.Text = "Storage-Flow -  msg-File (without Attachments)"
                        Else
                            Me.Text = "Ablage-Flow - msg-Datei (ohne Anhang)"
                        End If
                End Select

            ElseIf pDropType = "|MSGONLY|" Then
                If My.Application.User.Language = "de-DE" Then
                    Me.Text = "Ablage-Flow der msg-Datei (ohne Anhang)"
                Else
                    Me.Text = "Storage-Flow of msg-File (without Attachments)"
                End If
            ElseIf pDropType = "|ATTMNTEXTRACTED|" Or pDropType = "|OUTLOOK_ATTACHMENT|" Then
                My.Application.Globix.CURRENT_ISATTACHMENT = True

                If My.Application.User.Language = "de-DE" Then
                    Me.Text = "Ablage-Flow eines Email-Attachments"
                Else
                    Me.Text = "Storage-Flow of email-Attachment"
                End If
            ElseIf pDropType = "|FW_SIMPLEINDEXER|" Then

                If My.Application.User.Language = "de-DE" Then
                    Me.Text = "Ablage-Flow einer Folderwatch-Datei"
                Else
                    Me.Text = "Storage-Flow of Folderwatch-File"
                End If
            End If
        End If
    End Sub

    Private Sub SetFilePreview(ShowPreview As Boolean)
        If ShowPreview Then
            SplitContainerControl1.Collapsed = False
            PreviewFile()
            PreviewItem.Checked = True
        Else
            SplitContainerControl1.Collapsed = True
            PreviewItem.Checked = False
        End If
    End Sub
    Sub PreviewFile()
        Try
            DocumentViewer1.LoadFile(My.Application.Globix.CurrentWorkfile.FilePath)
        Catch ex As Exception
            Me.Visible = False
            FormHelper.ShowErrorMessage(ex, "Laden der Vorschau")
            Me.Visible = True
        End Try
    End Sub

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles SourceDeleteItem.ItemClick
        If SourceDeleteItem.Visibility <> DevExpress.XtraBars.BarItemVisibility.Never Then
            My.Application.Globix.DeleteOriginalFile = SourceDeleteItem.Checked
            My.UIConfig.Globix.DeleteOriginalFile = SourceDeleteItem.Checked
            My.SystemConfigManager.Save()
        End If
    End Sub

    Private Sub SkipItem_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles SkipItem.ItemClick
        My.Database.ExecuteNonQueryECM($"DELETE FROM TBGI_FILES_USER WHERE GUID = {My.Application.Globix.CurrentWorkfile.Id}")
        CancelAttempts = MAX_CANCEL_ATTEMPTS
        Close()
    End Sub

    Private Sub BarCheckItem3_CheckedChanged(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles chkMultiindexing.CheckedChanged
        If chkMultiindexing.Checked Then
            chkMultiindexing.Caption = "Active"
        Else
            chkMultiindexing.Caption = "Inactive"
        End If
    End Sub


    Private Sub checkItemPreselection_CheckedChanged(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles checkItemPreselection.CheckedChanged
        My.UIConfig.Globix.ProfilePreselection = checkItemPreselection.Checked
        My.SystemConfigManager.Save()
    End Sub
    Sub Refresh_Dokart()
        Try
            Dim oDocTypes As New List(Of DocType)
            Dim oSql = String.Format($"SELECT A.DOCTYPE_ID,A.USERNAME,DL.Doctype,A.OBJECT_ST_NAME, DL.Doctype_ID as IDBDoctype_ID,DL.LANG_CODE,A.SEQUENCE FROM VWGI_DOCTYPE_USER A INNER JOIN TBDD_DOKUMENTART DT ON A.DOCTYPE_ID = DT.GUID
INNER JOIN IDB.dbo.VWIDB_DOCTYPE_LANGUAGE DL ON DT.IDB_DOCTYPE_ID = DL.Doctype_ID WHERE A.AKTIV = 1 AND A.USERNAME = '{My.Application.User.UserName}' AND DL.LANG_CODE = '{My.Application.User.Language}' ORDER BY A.SEQUENCE")
            Dim oTable = Database.GetDatatable("VWGI_DOCTYPE_USER", oSql, ECM,
                                               pSortByColumn:="SEQUENCE",
                                               pFilterExpression:=$"AKTIV = 1 AND USERNAME = '{My.Application.User.UserName}' AND LANG_CODE = '{My.Application.User.Language}'")

            For Each oRow As DataRow In oTable.Rows
                Dim oDocType = New DocType With {
                    .Guid = oRow.Item("DOCTYPE_ID"),
                    .Name = oRow.Item("Doctype"),
                    .ObjectStore = oRow.Item("OBJECT_ST_NAME"),
                    .IDB_DoctypeID = oRow.Item("IDBDoctype_ID")
                }

                oDocTypes.Add(oDocType)
                cmbDocType.Properties.Items.Add(oDocType)
            Next

            DocTypes = oDocTypes
        Catch ex As Exception
            Me.Visible = False
            FormHelper.ShowErrorMessage(ex, "Laden des Profils")
            Me.Visible = True
        End Try
    End Sub


    Private Sub ComboBoxEdit1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbDocType.SelectedIndexChanged
        If cmbDocType.SelectedIndex <> -1 And FormLoaded = True Then
            Dim oSelectedItem As DocType = cmbDocType.SelectedItem

            ClearNotice()
            ClearError()

            pnlIndex.Controls.Clear()

            SelectedDocType = oSelectedItem
            'My.Application.Globix.CURRENT_DOCTYPE_DuplicateHandling = My.Application.Globix.CURR_DT_DOCTYPE.Rows(0).Item("DUPLICATE_HANDLING").ToString

            ManualIndexes = Refresh_IndexeMan(oSelectedItem.Guid)
            LoadIndexe_Man(ManualIndexes)

        End If
    End Sub
    Private Function Refresh_IndexeMan(dokartid As Integer) As List(Of ManualIndex)
        Dim oSql
        Try
            oSql = $"SELECT 
                    T1.BEZEICHNUNG AS DOKUMENTART, T.* 
                    FROM TBDD_INDEX_MAN T, 
                    TBDD_DOKUMENTART T1 
                    WHERE T.DOK_ID = T1.GUID AND 
                    T.DOK_ID = {dokartid} 
                    ORDER BY T.SEQUENCE"

            Dim oTable = My.Database.GetDatatable("VWDDINDEX_MAN", oSql, ECM,
                                                  pSortByColumn:="SEQUENCE",
                                                  pFilterExpression:=$"DOK_ID = {dokartid}")

            Dim oManualIndexes As New List(Of ManualIndex)

            For Each oRow As DataRow In oTable.Rows
                Dim oIndex As New ManualIndex With {
                    .Id = oRow.ItemEx(Of Integer)("GUID"),
                    .DocTypeId = oRow.ItemEx(Of Integer)("DOK_ID"),
                    .DocTypeName = oRow.ItemEx(Of String)("DOKUMENTART"),
                    .Name = oRow.ItemEx(Of String)("WD_INDEX"),
                    .InternalName = oRow.ItemEx(Of String)("INDEXNAME"),
                    .LabelCaption = oRow.ItemEx(Of String)("COMMENT"),
                    .DataType = oRow.ItemEx(Of String)("DATATYPE"),
                    .Sequence = oRow.ItemEx("SEQUENCE", 0),
                    .SQLCommand = oRow.ItemEx("SQL_RESULT", String.Empty),
                    .SQLConnection = oRow.ItemEx("CONNECTION_ID", 0),
                    .SQLSuggestion = oRow.ItemEx("SUGGESTION", String.Empty),
                    .DefaultValue = oRow.ItemEx("DEFAULT_VALUE", String.Empty),
                    .IsOptional = oRow.ItemEx(Of Integer)("OPTIONAL", False),
                    .IsMultiselect = oRow.ItemEx("MULTISELECT", False)
                }

                oManualIndexes.Add(oIndex)
            Next

            Return oManualIndexes
        Catch ex As Exception
            Logger.Error(ex)
            Me.Visible = False
            FormHelper.ShowErrorMessage(ex, "Unexpected error in Refresh_IndexeMan:")
            Me.Visible = True
            Return Nothing

        End Try
    End Function

    Private Sub LoadIndexe_Man(pManualIndexes As List(Of ManualIndex))
        Try
            Dim oScreen As New DigitalData.Modules.Windows.Screen()
            Dim oDpiScale = oScreen.GetScreenScaling(Me)

            Dim oControlCount As Integer = 1
            Dim oLabelPosition As Integer = 11 * oDpiScale
            Dim oControlPosition As Integer = 33 * oDpiScale

            Dim oControls As New ControlCreator(LogConfig, pnlIndex, Me) With {
                .OnControlChanged = AddressOf PrepareDependingControl,
                .OnLookupData = AddressOf GetLookupData
            }

            pnlIndex.Visible = True

            Logger.Info("Loading Indicies for Screen Scaling Factor [{0}]", oDpiScale)

            If pManualIndexes Is Nothing OrElse pManualIndexes.Count = 0 Then
                ShowError("Keine Manuellen Indizes für die " & vbNewLine & "Dokumentart " & cmbDocType.Text & " definiert")
                Logger.Info(" - Keine Manuellen Indizes für die " & vbNewLine & "Dokumentart " & cmbDocType.Text & " definiert")
            End If

            For Each oIndex As ManualIndex In pManualIndexes
                Dim MultiSelect As Boolean = oIndex.IsMultiselect
                Dim AddNewItems As Boolean = oIndex.AllowAddingItems
                Dim PreventDuplicates As Boolean = oIndex.PreventMultleValue
                Dim oControlName As String = oIndex.Name
                Dim oConnectionId = oIndex.SQLConnection
                Dim oDataType = oIndex.DataType

                If oDataType <> "BOOLEAN" Then
                    Dim oLabel = oControls.AddLabel(oControlName, oIndex.LabelCaption, oLabelPosition, oControlCount)
                    pnlIndex.Controls.Add(oLabel)
                End If

                'Dim oDefaultValue = Check_HistoryValues(oControlName, oIndex.DocTypeName)
                'If oDefaultValue Is Nothing Then
                '    'oDefaultValue = GetPlaceholderValue(oIndex.DefaultValue, My.Application.Globix.CURRENT_WORKFILE)
                'End If
                Dim oDefaultValue = GetPlaceholderValue(oIndex.DefaultValue, My.Application.Globix.CurrentWorkfile.FilePath)
                Dim oControl As Control = Nothing
                Dim oHasSqlCommand = (oConnectionId > 0 And oIndex.SQLCommand.Length > 0)
                Dim oNeedsLookup As Boolean = oHasSqlCommand Or MultiSelect = True

                Select Case oIndex.DataType
                    Case "BOOLEAN"
                        Dim oCheckbox = oControls.AddCheckBox(oControlName, oControlPosition, oDefaultValue, oIndex.LabelCaption)
                        oControl = oCheckbox

                    Case "INTEGER"
                        If oNeedsLookup Then
                            oControl = oControls.AddLookupControl(oControlName, oControlPosition, MultiSelect, oDataType, oIndex.SQLCommand, oConnectionId, oDefaultValue, AddNewItems, PreventDuplicates)
                        Else
                            oControl = oControls.AddTextBox(oControlName, oControlPosition, oDefaultValue, oDataType)
                        End If

                    Case "VARCHAR"
                        If oNeedsLookup Then
                            oControl = oControls.AddLookupControl(oControlName, oControlPosition, MultiSelect, oDataType, oIndex.SQLCommand, oConnectionId, oDefaultValue, AddNewItems, PreventDuplicates)
                        Else
                            oControl = oControls.AddTextBox(oControlName, oControlPosition, oDefaultValue, oDataType)
                        End If

                    Case "DATE"
                        oControl = oControls.AddDateTimePicker(oControlName, oControlPosition, oDataType)

                    Case Else
                        Dim omsg As String
                        If My.Application.User.Language = "de-DE" Then
                            omsg = "Bitte überprüfen Sie den Datentyp des hinterlegten Indexwertes!"
                        Else
                            omsg = "Please check Datatype of Indexvalue!"
                        End If
                        Me.Visible = False
                        Dim oResult = FormHelper.ShowWarningMessage(omsg, "Index Load")
                        Me.Visible = True
                        Logger.Warn("DataType [{0}] not implemented!", oIndex.DataType)
                End Select

                If Not IsNothing(oControl) Then
                    pnlIndex.Controls.Add(oControl)
                End If

                oControlCount += 1
                oLabelPosition += 50 * oDpiScale
                oControlPosition += 50 * oDpiScale
                'make y as height in fom
            Next
            Dim oPanelHeight = oControlPosition - 30

            If pnlIndex.Height < oPanelHeight Then
                If (Height - 315) < oPanelHeight Then
                    Height = (Height - 315) + oPanelHeight
                End If
                pnlIndex.Height = oPanelHeight
            End If

            SendKeys.Send("{TAB}")
        Catch ex As Exception
            Logger.Error(ex)
            Me.Visible = False
            FormHelper.ShowErrorMessage(ex, "Unexpected error in LoadIndexe_Man:")
            Me.Visible = True
        End Try
    End Sub
    Private Sub PrepareDependingControl(pControl As Control)
        If TypeOf pControl Is Label Then
            Exit Sub
        End If

        Try
            Dim oMeta = DirectCast(pControl.Tag, ControlCreator.ControlMeta)
            Dim oIndexName As String = oMeta.IndexName
            Dim oSQL = $"SELECT * FROM TBDD_INDEX_MAN WHERE SQL_RESULT LIKE '%{oIndexName}%' AND DOK_ID = {SelectedDocType.Guid}"
            Dim oDatatable As DataTable = My.Database.GetDatatableECM(oSQL)

            If Not IsNothing(oDatatable) Then
                Logger.Debug("Found [{0}] depending controls for [{1}]", oDatatable.Rows.Count, pControl.Name)

                For Each oRow As DataRow In oDatatable.Rows
                    Dim oControlName As String = NotNull(oRow.Item("NAME"), "")
                    Dim oConnectionId As Integer = NotNull(oRow.Item("CONNECTION_ID"), -1)
                    Dim oControlSql As String = NotNull(oRow.Item("SQL_RESULT"), "")

                    If oConnectionId = -1 Or oControlSql = String.Empty Then
                        Logger.Warn("Missing SQL Query or ConnectionId for Control [{0}]! Continuing.", oControlName)
                        Continue For
                    End If

                    oControlSql = Patterns2.ReplaceInternalValues(oControlSql)
                    oControlSql = Patterns2.ReplaceUserValues(oControlSql, My.Application.User)
                    oControlSql = Patterns2.ReplaceControlValues(oControlSql, pnlIndex)

                    Logger.Debug("Setting new value for [{0}]", oControlName)
                    SetDependingControlResult(oControlName, oControlSql, oConnectionId)
                Next
            End If
        Catch ex As Exception
            Logger.Error(ex)
        End Try
    End Sub
    Private Sub SetDependingControlResult(IndexName As String, pSqlCommand As String, SqlConnectionId As Integer)
        Try
            If pSqlCommand Is Nothing OrElse pSqlCommand = String.Empty Then
                Logger.Warn("New Value for Index [{0}] could not be set. Supplied SQL is empty.")
                Exit Sub
            End If

            Dim oDatatable As DataTable = My.Database.GetDatatable(pSqlCommand, SqlConnectionId)
            Dim oFoundControl As Control = Nothing

            For Each oControl As Control In pnlIndex.Controls
                If TypeOf oControl Is Label Then
                    Continue For
                End If

                Dim oMeta = DirectCast(oControl.Tag, ControlCreator.ControlMeta)
                Dim oIndex As String = oMeta.IndexName

                If oIndex = IndexName Then
                    oFoundControl = oControl
                    Exit For
                End If
            Next

            If oFoundControl Is Nothing Then
                Logger.Warn("Depending Control for Index [{0}] not found!", IndexName)
            End If

            If oDatatable Is Nothing Then
                Logger.Warn("Error in SQL Command: {0}", pSqlCommand)
            End If

            Select Case oFoundControl.GetType.Name
                Case GetType(DevExpress.XtraEditors.TextEdit).Name
                    If oDatatable.Rows.Count > 0 Then
                        Dim oFirstRow As DataRow = oDatatable.Rows.Item(0)

                        If oFirstRow.ItemArray.Length > 0 Then
                            Dim oValue = oFirstRow.Item(0).ToString()

                            Logger.Debug("Setting Value for TextEdit [{0}]: [{1}]", oFoundControl.Name, oValue)
                            DirectCast(oFoundControl, DevExpress.XtraEditors.TextEdit).Text = oValue
                        End If
                    End If
                Case GetType(LookupControl3).Name
                    Logger.Debug("Setting Value for LookupControl [{0}]: [{1}]", oFoundControl.Name, "DATATABLE")
                    DirectCast(oFoundControl, LookupControl3).Properties.DataSource = oDatatable
                Case GetType(Windows.Forms.ComboBox).Name
                    Logger.Debug("Setting Value for Combobox [{0}]: [{1}]", oFoundControl.Name, "DATATABLE")
                    DirectCast(oFoundControl, Windows.Forms.ComboBox).DataSource = oDatatable
                Case Else
                    Logger.Debug("Could not set depending control result for [{0}]", oFoundControl.GetType.Name)
            End Select
        Catch ex As Exception
            Logger.Error(ex)
        End Try
    End Sub
    Private Function GetLookupData(pLookup As LookupControl3, pSQLCommand As String, pConnectionId As Integer)

        Dim oConnectionString = Database.GetConnectionString(pConnectionId)
        'Dim oConnectionString = GetConnectionString(pConnectionId)
        oConnectionString = MSSQLServer.DecryptConnectionString(oConnectionString)

        If oConnectionString IsNot Nothing And pSQLCommand.Length > 0 Then
            Logger.Debug("Connection String (redacted): [{0}]", oConnectionString.Substring(0, 30))

            If Patterns2.HasComplexPatterns(pSQLCommand) Then
                Logger.Debug(" >>sql enthält Platzhalter und wird erst während der Laufzeit gefüllt!", False)
                Return Nothing
            Else
                pSQLCommand = Patterns2.ReplaceInternalValues(pSQLCommand)
                pSQLCommand = Patterns2.ReplaceUserValues(pSQLCommand, My.Application.User)

                Dim oDatatable = My.Database.GetDatatable(pSQLCommand, pConnectionId)
                Return oDatatable
            End If
        Else
            Logger.Warn("Connection String for control [{0}] is empty!", pLookup.Name)
            Return Nothing
        End If
    End Function
    Function GetPlaceholderValue(InputValue As String, FileName As String) As String
        Dim oResult As String = InputValue
        Dim oFileInfo As New FileInfo(FileName)

        Dim oPatterns As New Modules.Patterns.Patterns2(My.LogConfig)
        oResult = oPatterns.ReplaceInternalValues(oResult)
        oResult = oPatterns.ReplaceFileValues(oResult, oFileInfo)
        oResult = oPatterns.ReplaceUserValues(oResult, My.Application.User)

        Return oResult
    End Function

    Sub ShowError(text As String)
        labelError.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
        labelError.Caption = text
    End Sub

    Sub ClearError()
        labelError.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
        labelError.Caption = String.Empty
    End Sub

    Sub ShowNotice(text As String)
        labelNotice.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
        labelNotice.Caption = text
    End Sub

    Sub ClearNotice()
        labelNotice.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
        labelNotice.Caption = String.Empty
    End Sub

    Private Sub frmGlobix_Index_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        If File.Exists(My.Application.Globix.CurrentWorkfile.FilePath) Then
            Dim oMsg As String, oTitle As String
            Select Case CancelAttempts
                Case 0

                    If My.Application.User.Language = "de-DE" Then
                        oMsg = "Bitte indexieren Sie die Datei vollständig!" & vbNewLine & "(Abbruch 1 des Indexierungsvorgangs)"
                        oTitle = "Fehlende Eingaben"
                    Else
                        oMsg = "Please Index file completely" & vbNewLine & "(Abort 1 of Indexdialog)"
                        oTitle = "Missung Input"
                    End If
                    Me.TopMost = False
                    Me.Visible = False
                    Dim oResult = FormHelper.ShowWarningMessage(oMsg, oTitle)
                    Me.Visible = True
                    CancelAttempts += 1
                    e.Cancel = True
                Case 1

                    If My.Application.User.Language = "de-DE" Then
                        oMsg = "Sie brechen nun zum zweiten Mal den Indexierungsvorgang ab!" & vbNewLine & "Wollen Sie die Indexierung aller Dateien abbrechen?"
                        oTitle = "Fehlende Eingaben"
                    Else
                        oMsg = "You abort the indexdialog for the 2nd time!" & vbNewLine & "Do You want to abort indexing?"
                        oTitle = "Missung Input"
                    End If
                    Me.Visible = False
                    Dim oResult = FormHelper.ShowQuestionMessage(oMsg, oTitle)
                    Me.Visible = True
                    If oResult = DialogResult.Yes Then
                        Dim containsfw_file As Boolean = False
                        Try
                            My.Application.Globix.ABORT_INDEXING = True
                            Dim sql As String = $"SELECT * FROM TBGI_FILES_USER WHERE WORKED = 0 AND USER@WORK = '{My.Application.User.UserName}'"
                            Dim DT As DataTable = My.Database.GetDatatableECM(sql)

                            Dim anz = DT.Rows.Count
                            For Each Filerow As DataRow In DT.Rows
                                Dim filestring As String = Filerow.Item("FILENAME2WORK")
                                Dim handletype As String = Filerow.Item("HANDLE_TYPE")

                                If handletype = "|MSGONLY|" Or handletype = "|ATTMNTEXTRACTED|" Then
                                    Try
                                        System.IO.File.Delete(filestring)
                                    Catch ex As Exception

                                    End Try

                                ElseIf handletype.StartsWith("|FW") Then
                                    containsfw_file = True
                                End If
                            Next
                            'Zuerst die Daten des Ablaufs löschen
                            If My.Database.ExecuteNonQueryECM($"DELETE FROM TBGI_FILES_USER WHERE USER@WORK = '{My.Application.User.UserName}'") = True Then
                                If containsfw_file = True Then
                                    Me.Visible = False
                                    If My.Application.User.Language = "de-DE" Then
                                        FormHelper.ShowInfoMessage("Der Indexierungsprozess beinhaltete (auch) Dateien per Folderwatch!" & vbNewLine & "Diese Dateien wurden nicht gelöscht und verbleiben im Folderwatch-Verzeichnis!" & vbNewLine & "Bitte verschieben Sie die Dateien ggfls.", "Hinweis")
                                    Else
                                        FormHelper.ShowInfoMessage("The Indexingprocess contained (also) files from folderwatch!" & vbNewLine & "These files weren't deleted and will stay in the folderwatch-folder!" & vbNewLine & "Please move these files manually.", "Attention")
                                    End If
                                    Me.Visible = True
                                End If
                            End If


                        Catch ex As Exception
                            Logger.Error(ex)
                            Me.Visible = False
                            FormHelper.ShowErrorMessage(ex, "Unexpected Error in Abort Indexing")
                            Me.Visible = True
                        End Try

                        Try
                            My.Application.Globix.INDEXING_ACTIVE = False

                            DocumentViewer1.CloseDocument()
                            DocumentViewer1.Done()
                            WindowLocation.SaveFormLocationSize(Me)
                            My.Settings.Save()
                        Catch ex As Exception
                            Logger.Info(" - Unexpected error in Schliessen des Formulares - Fehler: " & vbNewLine & ex.Message)
                            Logger.Error(ex.Message)
                            Me.Visible = False
                            FormHelper.ShowErrorMessage(ex, "Unexpected error in FormClosing:")
                            Me.Visible = True
                        End Try

                        e.Cancel = False
                    Else
                        e.Cancel = True
                    End If
                Case Else
                    Try
                        My.Application.Globix.INDEXING_ACTIVE = False

                        DocumentViewer1.CloseDocument()
                        DocumentViewer1.Done()
                        WindowLocation.SaveFormLocationSize(Me)
                        My.Settings.Save()
                    Catch ex As Exception
                        Logger.Warn(" - Unexpected error in Schliessen des Formulares2 - Fehler: " & vbNewLine & ex.Message)
                        Logger.Error(ex)
                        Me.Visible = False
                        FormHelper.ShowErrorMessage(ex, "Unexpected error in FormClosing2:")
                        Me.Visible = True
                    End Try
            End Select
        Else
            My.Application.Globix.INDEXING_ACTIVE = False
        End If
    End Sub

    Private Async Function GlobixFlowNew(pDocType As DocType) As Threading.Tasks.Task(Of Boolean)
        Try
            ClearError()
            ClearNotice()
            Cursor = Cursors.WaitCursor

            Logger.Info("Validating user values")

            Dim oValidator As New ClassValidator(My.LogConfig, My.Application.Service.Client, ManualIndexes)
            If oValidator.ValidateControls(pnlIndex, pDocType) = False Then
                Return False
            End If

            Logger.Info("Collecting user values")

            Dim oValues = oValidator.GetControlValues(pnlIndex)

            Logger.Info("Preparing method parameters")

            Dim oFilePath As String = My.Application.Globix.CurrentWorkfile.FilePath
            Dim oObjectStore As String = SelectedDocType.ObjectStore
            Dim oIDBDoctypeId As Long = SelectedDocType.IDB_DoctypeID
            Dim oObjectKind As String = "DOC"
            Dim oProfileId As Integer = SelectedDocType.Guid
            Dim oAttributes As List(Of UserAttributeValue) = oValues
            Dim oOptions As New Options.ImportFileOptions

            Logger.Debug("FilePath: [{0}]", oFilePath)
            Logger.Debug("ObjectStore: [{0}]", oObjectStore)
            Logger.Debug("ObjectKind: [{0}]", oObjectKind)
            Logger.Debug("ProfileId: [{0}]", oProfileId)
            Logger.Debug("IDB DoctypeId: [{0}]", oIDBDoctypeId)

            Logger.Info("Running Import")

            Dim oResult = Await My.Application.Service.Client.Globix_ImportFileAsync(
                oFilePath, oProfileId, oAttributes, oObjectStore, oObjectKind, oIDBDoctypeId, oOptions)

            Logger.Info("Import result: [{0}]", oResult.OK)
            Logger.Info("Imported file got ObjectId [{0}]", oResult.ObjectId)

            If oResult.OK Then
                Return True
            Else
                Logger.Warn("Import failed with message: [{0}] and details [{1}]", oResult.ErrorMessage, oResult.ErrorDetails)
                Dim oMsg As String, oTitle As String
                If My.Application.User.Language = "de-DE" Then
                    oMsg = $"Die Datei wurde nicht verarbeitet.{vbNewLine}{vbNewLine}Fehler: {oResult.ErrorMessage}"
                    oTitle = "Achtung"
                Else
                    oMsg = $"Unexpected Error in FileFlow{vbNewLine}{vbNewLine}Fehler: {oResult.ErrorMessage}"
                    oTitle = "Attention"
                End If
                FormHelper.ShowWarningMessage(oMsg, oTitle)

                Return False
            End If

        Catch ex As Exception
            Logger.Error(ex)
            Me.TopMost = False
            FormHelper.ShowErrorMessage(ex, Text)
            Return False

        Finally
            Cursor = Cursors.Default

        End Try
    End Function

    Private Async Sub SimpleButton1_Click(sender As Object, e As EventArgs) Handles SimpleButton1.Click
        Dim oDokart As DocType = cmbDocType.SelectedItem

        If oDokart Is Nothing Then
            Exit Sub
        End If

        Logger.Info("Importing file with DocumentType [{0}]", oDokart.Name)
        Dim oResult = Await GlobixFlowNew(oDokart)
        If oResult = True Then
            oSuccess = True
            Dim oDEL As String = "DELETE FROM TBGI_FILES_USER WHERE GUID = " & My.Application.Globix.CurrentWorkfile.Id
            My.DatabaseECM.ExecuteNonQuery(oDEL)
            DocumentViewer1.CloseDocument()
            DocumentViewer1.Done()
            CancelAttempts = MAX_CANCEL_ATTEMPTS

            If My.Application.Globix.DeleteOriginalFile = True Or My.Application.Globix.CurrentWorkfile.HotfolderFile = True Then
                Logger.Info("File [" & My.Application.Globix.CurrentWorkfile.FilePath & "] will be deleted...")
                Try
                    System.IO.File.Delete(My.Application.Globix.CurrentWorkfile.FilePath)
                Catch ex As Exception
                    Logger.Error(ex)
                End Try
                Logger.Info("File [" & My.Application.Globix.CurrentWorkfile.FilePath & "] has been deleted.")
            End If
            Close()
        End If
    End Sub



    Private Sub PreviewItem_CheckedChanged(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles PreviewItem.CheckedChanged
        If FormLoaded Then
            SetFilePreview(PreviewItem.Checked)
        End If
    End Sub

    Private Sub checkItemTopMost_CheckedChanged(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles checkItemTopMost.CheckedChanged
        If FormLoaded Then
            My.UIConfig.Globix.TopMost = checkItemTopMost.Checked
            My.UIConfigManager.Save()
        End If
    End Sub

    Private Function GetMessageBoxArgs() As XtraMessageBoxArgs
        Dim oArgs As New XtraMessageBoxArgs With {
            .LookAndFeel = LookAndFeel,
            .Text = "Die Datei wurde erfolgreich verarbeitet!",
            .Caption = Text,
            .DoNotShowAgainCheckBoxVisible = True
        }
        AddHandler oArgs.Closed, AddressOf MessageboxClosed
        AddHandler oArgs.Load, AddressOf MessageboxLoad
        Return oArgs
    End Function

    Private Sub MessageboxClosed(sender As Object, e As XtraMessageBoxClosedArgs)
        Dim oShowMessageBoxNextTime = e.Visible
        My.UIConfig.Globix.ShowSuccessMessageBox = oShowMessageBoxNextTime
        My.UIConfigManager.Save()
    End Sub

    Private Sub MessageboxLoad(sender As Object, e As XtraMessageBoxLoadArgs)
        e.Visible = My.UIConfig.Globix.ShowSuccessMessageBox
    End Sub


End Class
