Imports Oracle.ManagedDataAccess.Client
Imports System.Text.RegularExpressions

Public Class SQLConfigAutoIndex
    Dim CurrentPosition As Integer = 0

    Dim CurrentTableType As String
   
    Private Sub btnVorschlag_Click(sender As Object, e As EventArgs) Handles btnVorschlag.Click
        TestSQL(cmbConnection.SelectedValue, SQL_ERGEBNISTextBox.Text)
    End Sub
    Private Sub TestSQL(conid As Integer, sql_command As String)
        Try
            Dim query As String = sql_command

            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
                    query = query.Replace(placeholder, replacement)
                Else
                    MsgBox("Bitte geben Sie für den Platzhalter " & placeholder & " einen Wert an!", MsgBoxStyle.Exclamation, "Fehlende Platzhalter Ersetzung")
                    Exit Sub
                End If
            Next

            Dim typeCS As String = DATABASE_ECM.GetScalarValue("SELECT SQL_PROVIDER FROM TBDD_CONNECTION WHERE GUID = " & conid)
            Dim dt As DataTable
            If typeCS.Length > 0 Then
                Dim CS As String
                CS = DATABASE_ECM.Get_ConnectionStringforID(cmbConnection.SelectedValue)
                If typeCS.ToUpper = "Oracle".ToUpper Then
                    LOGGER.Warn("Oracle is not supported!")
                    'dt = ClassDatabase.Oracle_Return_Datatable(query, CS, True)
                Else
                    'dt = ClassDatabase.Return_Datatable_CS(query, CS, True)
                    dt = DATABASE_ECM.GetDatatableWithConnection(query, CS)
                End If
            End If

            If Not IsNothing(dt) Then
                If dt.Rows.Count = 1 Then
                    If USER_LANGUAGE = "de-DE" Then
                        MsgBox("Es wurde genau 1 Datensatz zurückgegeben!", MsgBoxStyle.Information)
                    Else
                        MsgBox("Excactly 1 record was returned!", MsgBoxStyle.Information)
                    End If
                End If
                CURRENT_SQLRESULT = sql_command
                DTSQL_RESULT = dt
                frmSQL_Result.ShowDialog()
            End If

            'If ds IsNot Nothing Then
            '    dgvResult.DataSource = ds.Tables(0)
            'End If




            'Try
            '    Dim connectionString As String

            '    Dim i As Integer

            '    connectionString = ClassFormFunctions.GetConnectionString(conid)
            '    If connectionString <> "" Then
            '        If connectionString.Contains("Initial Catalog=") Then
            '            Dim sqlCnn As SqlClient.SqlConnection
            '            Dim sqlCmd As SqlClient.SqlCommand
            '            Dim adapter As New SqlClient.SqlDataAdapter
            '            Dim NewDataset As New DataSet
            '            sqlCnn = New SqlClient.SqlConnection(connectionString)
            '            sqlCnn.Open()
            '            sqlCmd = New SqlClient.SqlCommand(sql_Vorschlag, sqlCnn)
            '            adapter.SelectCommand = sqlCmd
            '            adapter.Fill(NewDataset)
            '            Dim msg As String
            '            For i = 0 To NewDataset.Tables(0).Rows.Count - 1
            '                msg &= NewDataset.Tables(0).Rows(i).Item(0) & vbNewLine
            '                If i = 30 Then
            '                    Exit For
            '                End If
            '            Next
            '            adapter.Dispose()
            '            sqlCmd.Dispose()
            '            sqlCnn.Close()
            '            MsgBox("Folgende Daten wurden erfolgreich abgerufen: " & vbNewLine & vbNewLine & msg & vbNewLine & vbNewLine & "Das Ergebnis wurd auf 30 Zeilen eingeschränkt!", MsgBoxStyle.Information)

            '        ElseIf connectionString.StartsWith("Data Source=") And connectionString.Contains(";Persist Security Info=True;User Id=") Then
            '            Dim sqlCnn As OracleConnection
            '            Dim sqlCmd As OracleCommand
            '            Dim adapter As OracleDataAdapter
            '            Dim NewDataset As DataSet
            '            sqlCnn = New OracleConnection(connectionString)
            '            ' Try
            '            sqlCnn.Open()
            '            sqlCmd = New OracleCommand(sql_Vorschlag, sqlCnn)
            '            adapter.SelectCommand = sqlCmd
            '            adapter.Fill(NewDataset)
            '            Dim msg As String
            '            For i = 0 To NewDataset.Tables(0).Rows.Count - 1
            '                msg &= NewDataset.Tables(0).Rows(i).Item(0) & vbNewLine
            '                If i = 30 Then
            '                    Exit For
            '                End If
            '            Next
            '            adapter.Dispose()
            '            sqlCmd.Dispose()
            '            sqlCnn.Close()
            '            MsgBox("Folgende Daten wurden erfolgreich abgerufen: " & vbNewLine & vbNewLine & msg & vbNewLine & vbNewLine & "Das Ergebnis wurd auf 30 Zeilen eingeschränkt!", MsgBoxStyle.Information)
            '        End If
            '    Else
            '        MsgBox("Keine gültige ConnectionID", MsgBoxStyle.Exclamation)
            '    End If

        Catch ex As Exception
            LOGGER.Info(" - Unexpected error in TestSQL - Fehler: " & vbNewLine & ex.Message)
            LOGGER.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Unexpected error in TestSQL:")
        End Try
    End Sub

    Private Sub frmSQLSuggestion_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            'TODO: Diese Codezeile lädt Daten in die Tabelle "MyDataset.TBDD_CONNECTION". Sie können sie bei Bedarf verschieben oder entfernen.
            Me.TBDD_CONNECTIONTableAdapter.Connection.ConnectionString = MyConnectionString
            Me.TBDD_INDEX_MANTableAdapter.Connection.ConnectionString = MyConnectionString
            Me.TBDD_CONNECTIONTableAdapter.Fill(Me.MyDataset.TBDD_CONNECTION)
            Dim DT As DataTable = DATABASE_ECM.GetDatatable("SELECT * FROM TBDD_INDEX_AUTOM WHERE GUID = " & CURRENT_INDEXAUTO)
            If DT.Rows.Count = 1 Then
                Me.cmbConnection.SelectedValue = DT.Rows(0).Item("CONNECTION_ID")
                SQL_ERGEBNISTextBox.Text = DT.Rows(0).Item("SQL_RESULT")
            End If
            Try
                Me.TBDD_INDEX_MANTableAdapter.Fill(Me.MyDataset.TBDD_INDEX_MAN, CURRENT_DOKART_ID)
                Add_ManualIndexe()
            Catch ex As System.Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in Load Manual Indices:")
            End Try
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in LoadFormData:")
        End Try

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        frmConnections.ShowDialog()
        Me.TBDD_CONNECTIONTableAdapter.Fill(Me.MyDataset.TBDD_CONNECTION)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles btnsave.Click
        Try
            Dim origresultstring = DATABASE_ECM.GetScalarValue("SELECT SQL_RESULT FROM TBDD_INDEX_AUTOM WHERE GUID = " & CURRENT_INDEXAUTO)
            'Dim origConnection = DATABASE_ECM.GetScalarValue("SELECT CONNECTION_ID FROM TBDD_INDEX_AUTOM WHERE GUID = " & CURRENT_INDEXAUTO, True)
            'If origConnection Is DBNull Then

            'End If
            Dim insresultstring = SQL_ERGEBNISTextBox.Text.Replace("'", "''")
            If insresultstring <> origresultstring Then
                Dim cmd As String
                cmd = "UPDATE TBDD_INDEX_AUTOM SET CONNECTION_ID = " & cmbConnection.SelectedValue & ", SQL_RESULT = '" & insresultstring & "', CHANGED_WHO = '" &
                Environment.UserName & "' WHERE GUID = " & CURRENT_INDEXAUTO
                If DATABASE_ECM.ExecuteNonQuery(cmd) = True Then
                    If USER_LANGUAGE = "de-DE" Then
                        lblSave.Text = "SQL-Daten gespeichert - " & Now
                    Else
                        lblSave.Text = "SQL-Data saved - " & Now
                    End If
                    Me.lblSave.Visible = True
                Else
                    Me.lblSave.Visible = False
                End If

            Else
                Me.lblSave.Visible = True
                lblSave.Text = "Keine Änderungen vorhanden"
                If USER_LANGUAGE = "de-DE" Then
                    lblSave.Text = "Keine Änderungen vorhanden"
                Else
                    lblSave.Text = "No changes"
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in Save SQL IndexAuto:")
        End Try
    End Sub

    Private Sub SQL_ERGEBNISTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles SQL_ERGEBNISTextBox.KeyPress
        If e.KeyChar = Convert.ToChar(1) Then
            DirectCast(sender, TextBox).SelectAll()
            e.Handled = True
        End If
    End Sub
    Sub Add_ManualIndexe()
        Try

        Catch ex As Exception
            MsgBox("Error in Add Manual Indices: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub btnaddManualIdx_Click(sender As Object, e As EventArgs) Handles btnaddManualIdx.Click
        If cmbManualIDX.SelectedIndex <> -1 Then
            If Not cmbManualIDX.Text = String.Empty Then
                Dim placeholder As String = "[%" & cmbManualIDX.Text & "]"
                SQL_ERGEBNISTextBox.Text = SQL_ERGEBNISTextBox.Text.Insert(CurrentPosition, placeholder)
            End If
        End If
    End Sub

    ReadOnly AtPlaceholderPattern As String = "\[%{1}[a-zA-Z0-9\!\$\&\/\(\)\=\?\,\.\-\;\:_öÖüÜäÄ\#\'\+\*\~\{\}\@\€\<\>\ ]+]{1}"

    Private Sub SQL_ERGEBNISTextBox_KeyUp(sender As Object, e As KeyEventArgs) Handles SQL_ERGEBNISTextBox.KeyUp
        CurrentPosition = SQL_ERGEBNISTextBox.SelectionStart
    End Sub

    Private Sub SQL_ERGEBNISTextBox_MouseUp(sender As Object, e As MouseEventArgs) Handles SQL_ERGEBNISTextBox.MouseUp
        CurrentPosition = SQL_ERGEBNISTextBox.SelectionStart
    End Sub
    Private Sub SQL_ERGEBNISTextBox_TextChanged(sender As Object, e As EventArgs) Handles SQL_ERGEBNISTextBox.TextChanged
        CurrentPosition = SQL_ERGEBNISTextBox.SelectionStart
        If SQL_ERGEBNISTextBox.Text.Trim().Count = 0 Then
            dgvPlaceholders.Enabled = False
        Else
            dgvPlaceholders.Enabled = True
        End If
        CheckForPlaceholders()
    End Sub
    Public Property Value() As String
        Get
            Return SQL_ERGEBNISTextBox.Text
        End Get
        Set(value As String)
            SQL_ERGEBNISTextBox.Text = value
        End Set
    End Property
    Private Sub CheckForPlaceholders()
        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 cmbSelectConditions_Changed(sender As Object, e As EventArgs) Handles cmbSelectColumns.SelectedIndexChanged, cmbFromTables.SelectedIndexChanged, cmbWhereColumns.SelectedIndexChanged, cmbWhereOperator.SelectedIndexChanged, txtCondition.TextChanged
        Try
            Dim sql = ""
            Dim column, table, column2, op, condition As String
            Dim isNumberRegex = New Regex("^\d+$")

            column = cmbSelectColumns.Text
            table = cmbFromTables.Text
            column2 = cmbWhereColumns.Text
            op = cmbWhereOperator.Text
            condition = txtCondition.Text

            If column <> "" And table <> "" Then
                sql = String.Format("SELECT [{0}] FROM [{1}]", column, table)

                If column2 <> "" And op <> "" And condition <> "" Then

                    If isNumberRegex.Match(condition).Success = False Then
                        condition = String.Format("'{0}'", condition)
                    End If

                    sql &= String.Format(" WHERE [{0}] {1} {2}", column2, op, condition)
                ElseIf column2 <> "" And op <> "" And condition = "" Then
                    sql &= String.Format(" WHERE [{0}] {1}", column2, op)
                ElseIf column2 <> "" And op = "" And condition = "" Then
                    sql &= String.Format(" WHERE '{0}'", column2)
                End If

            End If

            SQL_ERGEBNISTextBox.Text = sql
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in cmbSelectConditions_Changed:")
        End Try

    End Sub

    Private Sub radioTable_CheckedChanged(sender As Object, e As EventArgs) Handles radioTable.CheckedChanged
        If radioTable.Checked Then
            CurrentTableType = "TABLE"
        End If
        EnableTables()
    End Sub

    Private Sub radioView_CheckedChanged(sender As Object, e As EventArgs) Handles radioView.CheckedChanged
        If radioView.Checked Then
            CurrentTableType = "VIEW"
        End If
        EnableTables()
    End Sub
    Private Sub cmbFromTables_SelectedIndexChanged() Handles cmbFromTables.SelectedIndexChanged
        If cmbFromTables.Text <> "" Then
            EnableColumns()
        Else
            EnableColumns(False)
        End If
    End Sub
    Private Sub EnableTables()
        cmbFromTables.Enabled = True
    End Sub
    Private Sub EnableColumns(Optional enabled = True)
        cmbSelectColumns.Enabled = enabled
        cmbWhereColumns.Enabled = enabled
    End Sub
    Private Sub cmbTables_DropDown(sender As Object, e As EventArgs) Handles cmbFromTables.DropDown
        Try
            Dim type As String

            If CurrentTableType = "TABLE" Then
                type = "'BASE TABLE'"
            ElseIf CurrentTableType = "VIEW" Then
                type = "'VIEW'"
            End If

            Dim typeCS As String = DATABASE_ECM.GetScalarValue("SELECT SQL_PROVIDER FROM TBDD_CONNECTION WHERE GUID = " & cmbConnection.SelectedValue)
            Dim dt As DataTable
            If typeCS.Length > 0 Then
                Dim oSQL As String = "SELECT TABLE_NAME from information_schema.tables where TABLE_TYPE = " & type & " ORDER BY TABLE_NAME"
                Dim CS As String
                CS = DATABASE_ECM.Get_ConnectionStringforID(cmbConnection.SelectedValue)
                If typeCS.ToUpper = "Oracle".ToUpper Then


                    'If type = "'VIEW'" Then
                    '    'DB-Abfrage für alle Views definieren 
                    '    oSQL = "select VIEW_NAME from USER_VIEWS"
                    'Else
                    '    'DB-Abfrage für alle Tables definieren 
                    '    oSQL = "select TABLE_NAME from USER_TABLES"
                    'End If
                    'dt = ClassDatabase.Oracle_Return_Datatable(oSQL, CS, True)
                    LOGGER.Warn("Oracle is not supported!")
                Else
                    oSQL = "SELECT TABLE_NAME from information_schema.tables where TABLE_TYPE = " & type & " ORDER BY TABLE_NAME"
                    'dt = ClassDatabase.Return_Datatable_CS(SQL, CS, True)
                    dt = DATABASE_ECM.GetDatatableWithConnection(oSQL, CS)
                End If
                If dt IsNot Nothing Then
                    cmbFromTables.Items.Clear()
                    For Each row As DataRow In dt.Rows
                        cmbFromTables.Items.Add(row.Item(0))
                    Next
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in cmbTables_DropDown:")
        End Try

    End Sub
    Private Sub cmbColumns_DropDown(sender As Object, e As EventArgs) Handles cmbSelectColumns.DropDown
        Dim table = cmbFromTables.Text
        GetColumns(table, cmbSelectColumns)
    End Sub
    Private Sub GetColumns(tableName As String, ByRef combobox As ComboBox)
        Try
            Dim CS As String
            CS = DATABASE_ECM.Get_ConnectionStringforID(cmbConnection.SelectedValue)
            Dim typeCS As String = DATABASE_ECM.GetScalarValue("SELECT SQL_PROVIDER FROM TBDD_CONNECTION WHERE GUID = " & cmbConnection.SelectedValue)
            Dim SQL As String
            Dim DT As DataTable
            If typeCS.ToUpper = "Oracle".ToUpper Then
                'SQL = "select COLUMN_NAME from USER_TAB_COLS where TABLE_NAME='" & tableName & "' order by COLUMN_NAME"
                'DT = ClassDatabase.Oracle_Return_Datatable(SQL, CS, True)
                LOGGER.Warn("Oracle is not supported!")
            Else
                SQL = "SELECT name FROM sys.columns WHERE object_id = OBJECT_ID('" & tableName & "') ORDER BY name"
                'DT = ClassDatabase.Return_Datatable_CS(SQL, CS, True)
                DT = DATABASE_ECM.GetDatatableWithConnection(SQL, CS)
            End If

            If DT IsNot Nothing Then
                combobox.Items.Clear()
                For Each row As DataRow In DT.Rows
                    combobox.Items.Add(row.Item(0))
                Next
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in GetColumns:")
        End Try

    End Sub

    Private Sub cmbWhereColumns_DropDown(sender As Object, e As EventArgs) Handles cmbWhereColumns.DropDown
        Dim table = cmbFromTables.Text
        GetColumns(table, cmbWhereColumns)
    End Sub

    Private Sub btnaddWindowPAram_Click(sender As Object, e As EventArgs) Handles btnaddWindowPAram.Click
        If cmbwindowsParam.SelectedIndex <> -1 Then
            If Not cmbwindowsParam.Text = String.Empty Then
                Dim placeholder As String
                Dim pattern As String = ""

                If USER_LANGUAGE = "de-DE" Then
                    Select Case cmbwindowsParam.Text.ToString.ToUpper
                        Case "Dateiname (mit Endung)".ToUpper
                            pattern = "$filename_ext".ToUpper
                        Case "Dateiname (ohne Endung)".ToUpper
                            pattern = "$filename".ToUpper
                        Case "Dateiendung".ToUpper
                            pattern = "$extension".ToUpper
                        Case "Datei Erstelldatum".ToUpper
                            pattern = "$FileCreateDate".ToUpper
                        Case "Datei Erstellt wer".ToUpper
                            pattern = "$FileCreatedWho".ToUpper
                        Case "Aktuelles Datum (DD.MM.YYYY)".ToUpper
                            pattern = "$DateDDMMYYY".ToUpper
                        Case "Username"
                            pattern = "$Username".ToUpper
                        Case "Usercode"
                            pattern = "$Usercode".ToUpper
                    End Select
                Else
                    Select Case cmbwindowsParam.Text.ToString.ToUpper
                        Case "Filename (with Extension)".ToUpper
                            pattern = "$filename_ext".ToUpper
                        Case "Filename (no Extension)".ToUpper
                            pattern = "$filename".ToUpper
                        Case "Fileextension".ToUpper
                            pattern = "$extension".ToUpper
                        Case "File Created At".ToUpper
                            pattern = "$FileCreateDate".ToUpper
                        Case "File Created Who".ToUpper
                            pattern = "$FileCreatedWho".ToUpper
                        Case "Current Date (DD.MM.YYYY)".ToUpper
                            pattern = "$DateDDMMYYY".ToUpper
                        Case "Username"
                            pattern = "$Username".ToUpper
                        Case "Usercode"
                            pattern = "$Usercode".ToUpper
                    End Select
                End If

                placeholder = "[%" & pattern & "]"
                If placeholder <> "" Then
                    SQL_ERGEBNISTextBox.Text = SQL_ERGEBNISTextBox.Text.Insert(CurrentPosition, placeholder)
                End If

            End If
        End If
    End Sub
End Class