Public Class frmSQLDesigner
    Dim CurrentPosition As Integer = 0
    Dim CurrentPlaceholders As New Placeholders()
    Dim CurrentTableType As String
    Dim AtPlaceholderPattern As String = "\[%{1}[a-zA-Z0-9\!\$\&\/\(\)\=\?\,\.\-\;\:_öÖüÜäÄ\#\'\+\*\~\{\}\@\€\<\>\ ]+]{1}" '"\[%[0-9A-Za-z_-]{1,}\]"
    Public Class Placeholders
        Public Property RecordId As Integer
        Public Property ParentRecordId As Integer
        Public Property FormId As Integer
    End Class

    Public Property SQLCommand() As String
        Get
            Return SQL_COMMANDTextBox.Text
        End Get
        Set(value As String)
            SQL_COMMANDTextBox.Text = value
        End Set
    End Property

    Public Property ConnectionID
    Public AutoAttributID
    Public Property DesignType As String

    Private Sub frmSQLDesigner_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim oSQL
        lblSaveFinalIndex.Visible = False

        If DesignType = "GI_ATTRIBUTE_MAN" Then
            EnDisable_Man_Attribute(False)
        Else
            EnDisable_Man_Attribute(True)
            oSQL = "Select * From TBDD_INDEX_MAN WHERE ACTIVE = 1"
            Dim oDT = My.DatabaseECM.GetDatatable(oSQL)
            cmbAttributeMan.DataSource = oDT
            cmbAttributeMan.DisplayMember = oDT.Columns("WD_INDEX").ColumnName

            oSQL = $"Select * From TBDD_INDEX_AUTOM WHERE ACTIVE = 1 AND GUID <> {AutoAttributID}"
            Dim oDTAA = My.DatabaseECM.GetDatatable(oSQL)
            cmbAttributeAuto.DataSource = oDTAA
            cmbAttributeAuto.DisplayMember = oDTAA.Columns("INDEXNAME").ColumnName
            EnDisable_Auto_Attribute(True)

        End If
        If DesignType = "SQL_OVERVIEW" Then
            cmbConnection.Enabled = False
            'btnShowConnections.Enabled = False
        Else
            cmbConnection.Enabled = True
            oSQL = "SELECT * FROM TBDD_CONNECTION WHERE AKTIV = 1"
            Dim oDT As DataTable = My.DatabaseECM.GetDatatable(oSQL)
            cmbConnection.DataSource = oDT
            cmbConnection.DisplayMember = oDT.Columns("Bezeichnung").ColumnName
            cmbConnection.ValueMember = oDT.Columns("GUID").ColumnName
            If Not IsNothing(ConnectionID) Then
                If IsNumeric(ConnectionID) Then
                    cmbConnection.SelectedValue = ConnectionID
                End If

            End If

            'btnShowConnections.Enabled = True
        End If

    End Sub
    Private Sub SQL_COMMANDTextBox_TextChanged(sender As Object, e As EventArgs) Handles SQL_COMMANDTextBox.TextChanged, SQL_COMMANDTextBox.Click
        CurrentPosition = SQL_COMMANDTextBox.SelectionStart

        If SQL_COMMANDTextBox.Text.Trim().Count = 0 Then
            dgvPlaceholders.Enabled = False
        Else
            dgvPlaceholders.Enabled = True
        End If

        CheckForPlaceholders()
    End Sub
    Sub EnDisable_Man_Attribute(bool As Boolean)
        lblAttributeMan.Visible = bool
        cmbAttributeMan.Visible = bool
        btnAddAttributeMan.Visible = bool
    End Sub
    Sub EnDisable_Auto_Attribute(bool As Boolean)
        lblAttributeAuto.Visible = bool
        cmbAttributeAuto.Visible = bool
        btnAddAttributeAuto.Visible = bool
    End Sub
    Private Sub CheckForPlaceholders()
        Dim text As String = SQL_COMMANDTextBox.Text
        dgvPlaceholders.Rows.Clear()

        Dim patterns As List(Of clsPatterns.Pattern) = clsPatterns.GetAllPatterns(text)

        For Each pattern In patterns
            dgvPlaceholders.Rows.Add({pattern.ToString, ""})
        Next

        'Dim count As Integer = 0
        'Dim text As String = Me.Value
        'Dim atPlaceholderRegex = New Regex(AtPlaceholderPattern, RegexOptions.IgnoreCase)
        'Dim matches As MatchCollection = atPlaceholderRegex.Matches(text)
        'dgvPlaceholders.Rows.Clear()
        'For Each match As Match In matches
        '    dgvPlaceholders.Rows.Add({match.Value, ""})
        'Next
    End Sub
    Private Sub InsertAtSelection(str As String)
        Dim altePosition As Integer = SQL_COMMANDTextBox.SelectionStart()
        SQL_COMMANDTextBox.Text = SQL_COMMANDTextBox.Text.Insert(altePosition, str)
        SQL_COMMANDTextBox.SelectionStart = altePosition + str.Length
    End Sub

    Private Sub btnTestSQL_Click(sender As Object, e As EventArgs) Handles btnTestSQL.Click
        Try
            Dim query As String = SQL_COMMANDTextBox.Text

            For Each row As DataGridViewRow In dgvPlaceholders.Rows
                Dim placeholder As String = row.Cells(0).Value
                Dim replacement As String = row.Cells(1).Value

                ' Wenn Ersetzung ausgefüllt wurde, Platzhalter damit ersetzen
                If Not String.IsNullOrEmpty(replacement) Then
                    Dim pattern As New clsPatterns.Pattern(placeholder)

                    query = clsPatterns.ReplacePattern(query, pattern.Type, replacement)
                Else
                    MsgBox("Bitte geben Sie für den Platzhalter " & placeholder & " einen Wert an!", MsgBoxStyle.Exclamation, "Fehlende Platzhalter Ersetzung")
                    Exit Sub
                End If
            Next
            MsgBox(cmbConnection.SelectedValue)
            Dim oconString = My.DatabaseECM.Get_ConnectionStringforID(cmbConnection.SelectedValue)
            MsgBox(oconString)
            Dim decryptedConString = My.DatabaseECM.DecryptConnectionString(oconString)
            MsgBox(decryptedConString)
            Dim oDT = My.DatabaseECM.GetDatatableWithConnection(query, decryptedConString)


            If oDT IsNot Nothing Then
                dgvResult.DataSource = oDT
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub SimpleButton1_Click(sender As Object, e As EventArgs) Handles SimpleButton1.Click
        SQLCommand = SQL_COMMANDTextBox.Text
        ConnectionID = cmbConnection.SelectedValue
        Me.Close()
    End Sub

    Private Sub btnAddAttributeMan_Click(sender As Object, e As EventArgs) Handles btnAddAttributeMan.Click
        If cmbAttributeMan.SelectedIndex <> -1 Then
            Dim value As String = clsPatterns.WrapPatternValue(clsPatterns.PATTERN_ATTR_MAN, cmbAttributeMan.Text)
            InsertAtSelection(value)
        End If
    End Sub

    Private Sub btnAddStatic_Click(sender As Object, e As EventArgs) Handles btnAddStatic.Click
        If cmbStatic.SelectedIndex <> -1 Then
            Dim value As String = clsPatterns.WrapPatternValue(clsPatterns.PATTERN_INT, cmbStatic.Text)
            InsertAtSelection(value)
        End If
    End Sub

    Private Sub btnAddUser_Click(sender As Object, e As EventArgs) Handles btnAddUser.Click
        If cmbUser.SelectedIndex <> -1 Then
            Dim value As String = clsPatterns.WrapPatternValue(clsPatterns.PATTERN_USER, cmbUser.Text)
            InsertAtSelection(value)
        End If
    End Sub
End Class