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

Public Class frmSQL_DESIGNER
    'Private _windreamPM As ClassPMWindream

    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 SQLConnectionId As Integer
        Get
            Return cmbConnection.SelectedValue
        End Get
        Set(value As Integer)
            cmbConnection.SelectedValue = value
        End Set
    End Property

    Public Property ConnectionID As Integer
    Private Property IndexID As Integer
    Private Property DocTypeId As Integer

    Public Sub New(IndexId As Integer, DocTypeId As Integer)
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        Me.IndexID = IndexId
        Me.DocTypeId = DocTypeId
    End Sub

    Private Sub TBPM_PROFILE_FINAL_INDEXINGBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
        Validate()
        'TableAdapterManager.UpdateAll(Me.DD_DMSLiteDataSet)
    End Sub
    Private Sub frmSQL_FINAL_INDICES_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            lblSaveFinalIndex.Visible = False

            If Not String.IsNullOrEmpty(SQLCommand) Then
                SQL_COMMANDTextBox.Text = SQLCommand
            End If

            LoadConnections()
            LoadControls()

            cmbConnection.FindStringExact(ConnectionID)

            'TBDD_CONNECTIONTableAdapter.Connection.ConnectionString = MyConnectionString
            'TBDD_CONNECTIONTableAdapter.Fill(DD_DMSLiteDataSet.TBDD_CONNECTION)

            ' CURRENT_DT_SQL_CONFIG_TABLE = DATABASE_ECM.GetDatatable(String.Format("SELECT T.CONNECTION_ID,T1.BEZEICHNUNG AS 'CON_STRING',ISNULL(T.SQL_COMMAND,'') AS 'SQL_COMMAND' FROM TBPM_PROFILE_FINAL_INDEXING T, TBDD_CONNECTION T1 WHERE T.CONNECTION_ID = T1.GUID AND T.GUID = {0}", CURRENT_INDEX_ID), True)
            'If (CURRENT_DESIGN_TYPE = "INPUT_INDEX") Or CURRENT_DESIGN_TYPE = "FINAL_INDEX" Then
            '    If CURRENT_DT_SQL_CONFIG_TABLE.Rows.Count = 1 Then
            '        cmbConnection.SelectedValue = CURRENT_DT_SQL_CONFIG_TABLE.Rows(0).Item("CONNECTION_ID")
            '        cmbConnection.FindStringExact(CURRENT_DT_SQL_CONFIG_TABLE.Rows(0).Item("CON_STRING"))
            '    End If

            '    Dim oSQL = String.Format("SELECT NAME FROM TBPM_PROFILE_CONTROLS WHERE PROFIL_ID = {0} AND CTRL_TYPE <> 'LBL' ORDER BY NAME", CURRENT_ProfilGUID)
            '    Dim oDatatable As DataTable = DATABASE_ECM.GetDatatable(oSQL, True)
            '    cmbControls.DataSource = oDatatable
            '    cmbControls.DisplayMember = oDatatable.Columns(0).ColumnName
            '    cmbControls.Visible = True
            '    lblControls.Visible = True
            '    btnAddControl.Visible = True

            '    cmbIndexe.Items.Clear()
            '    If IDB_ACTIVE = False Then
            '        Dim oIndicies = WINDREAM.GetIndicesByObjecttype(CURRENT_OBJECTTYPE)
            '        If oIndicies IsNot Nothing Then
            '            For Each index As String In oIndicies
            '                cmbIndexe.Items.Add(index)
            '            Next
            '            cmbIndexe.SelectedIndex = -1
            '        End If
            '        'cmbIndexe.Enabled = True
            '        'lbIndexe.Enabled = True
            '        'btnAddIndex.Enabled = True
            '    Else
            '        Dim oAttributes = IDBData.GetIndicesByBE(CURRENT_OBJECTTYPE)
            '        If oAttributes IsNot Nothing Then
            '            For Each oAttribute As String In oAttributes
            '                cmbIndexe.Items.Add(oAttribute)
            '            Next
            '            cmbIndexe.SelectedIndex = -1
            '        End If

            '        'cmbIndexe.Enabled = False
            '        'lbIndexe.Enabled = False
            '        'btnAddIndex.Enabled = False
            '    End If

            'Else
            '    cmbControls.Visible = False
            '    lblControls.Visible = False
            '    btnAddControl.Visible = False
            '    cmbIndexe.Visible = False
            '    lbIndexe.Visible = False
            '    btnAddIndex.Visible = False
            'End If
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Unexpected Error while loading form: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    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
    Private Sub CheckForPlaceholders()
        Dim text As String = SQL_COMMANDTextBox.Text
        dgvPlaceholders.Rows.Clear()

        Dim patterns As List(Of ClassPatterns.Pattern) = ClassPatterns.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 btnTestSQL_Click(sender As Object, e As EventArgs) Handles btnTestSQL.Click
        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 ClassPatterns.Pattern(placeholder)

                query = ClassPatterns.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

        Dim ds As DataSet = ExecuteWithConnection(cmbConnection.SelectedValue, query)



        If ds IsNot Nothing Then
            GridControl1.DataSource = ds.Tables(0)
        End If
    End Sub
    Private Function ExecuteWithConnection(connectionId As Integer, sql As String) As DataSet
        Try

            Dim connectionString As String

            connectionString = DATABASE_ECM.Get_ConnectionStringforID(connectionId)

            If connectionString <> "" Then

                If (connectionString.StartsWith("Server=") Or connectionString.StartsWith("Data Source")) And (connectionString.Contains("Database=") Or connectionString.Contains("Initial Catalog=")) Then
                    Dim sqlConnection As SqlClient.SqlConnection
                    Dim sqlCommand As SqlClient.SqlCommand
                    Dim sqlAdapter As New SqlClient.SqlDataAdapter
                    Dim dataset As New DataSet

                    sqlConnection = New SqlClient.SqlConnection(connectionString)
                    sqlConnection.Open()

                    sqlCommand = New SqlClient.SqlCommand(sql, sqlConnection)

                    sqlAdapter.SelectCommand = sqlCommand
                    sqlAdapter.Fill(dataset)

                    Return dataset
                ElseIf connectionString.Contains("dsn=") Then 'ODBC-Connection
                    Dim sqlConnection As Odbc.OdbcConnection
                    Dim sqlCommand As Odbc.OdbcCommand
                    Dim sqlAdapter As New Odbc.OdbcDataAdapter
                    Dim dataset As New DataSet

                    sqlConnection = New Odbc.OdbcConnection(connectionString)
                    sqlConnection.Open()

                    sqlCommand = New Odbc.OdbcCommand(sql, sqlConnection)

                    sqlAdapter.SelectCommand = sqlCommand
                    sqlAdapter.Fill(dataset)

                    Return dataset
                Else
                    LOGGER.Debug(" >> It's an Oracle-Connection (ExecuteWithConnection)", False)
                    Dim sqlConnection As OracleConnection
                    Dim sqlCommand As OracleCommand
                    Dim sqlAdapter As New OracleDataAdapter
                    Dim dataset As New DataSet

                    sqlConnection = New OracleConnection(connectionString)
                    sqlConnection.Open()

                    sqlCommand = New OracleCommand(sql, sqlConnection)

                    sqlAdapter.SelectCommand = sqlCommand
                    sqlAdapter.Fill(dataset)

                    Return dataset
                End If
            Else
                MsgBox("Keine gültige ConnectionID", MsgBoxStyle.Exclamation)
            End If

        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info(" - Unvorhergesehener Fehler bei TestSQL - Fehler: " & vbNewLine & ex.Message)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei TestSQL:")
            Return Nothing
        End Try
    End Function



    Private Sub btnSaveSQLCommand_Click(sender As Object, e As EventArgs) Handles btnSaveSQLCommand.Click
        ' SQL wird nicht hier, sondern in frmAdministration gespeichert
        lblSaveFinalIndex.Visible = True
        lblSaveFinalIndex.Text = "SQL für finalen Index wurde erfolgreich gespeichert! " & Now.ToString
        SQLCommand = SQL_COMMANDTextBox.Text
    End Sub

    Private Sub btnAddControl_Click(sender As Object, e As EventArgs) Handles btnAddControl.Click
        If cmbControls.SelectedIndex <> -1 Then
            Dim value As String = ClassPatterns.WrapPatternValue(ClassPatterns.PATTERN_CTRL, cmbControls.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 = ClassPatterns.WrapPatternValue(ClassPatterns.PATTERN_INT, cmbStatic.Text)
            InsertAtSelection(value)
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnAddIndex.Click
        If cmbIndexe.SelectedIndex <> -1 Then
            Dim oValue As String
            'If IDB_ACTIVE = False Then
            '    oValue = ClassPatterns.WrapPatternValue(ClassPatterns.PATTERN_WMI, cmbIndexe.Text)
            'Else
            '    oValue = ClassPatterns.WrapPatternValue(ClassPatterns.PATTERN_IDBA, cmbIndexe.Text)
            'End If

            InsertAtSelection(oValue)
        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 = ClassPatterns.WrapPatternValue(ClassPatterns.PATTERN_USER, cmbUser.Text)
            InsertAtSelection(value)
        End If
    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 LoadConnections()
        Try
            Dim oDatatable As DataTable = DATABASE_ECM.GetDatatable("SELECT * FROM TBDD_CONNECTION")

            cmbConnection.ValueMember = "GUID"
            cmbConnection.DisplayMember = "BEZEICHNUNG"
            cmbConnection.DataSource = oDatatable

            Dim oConnectionName As String = oDatatable.Select($"GUID = {ConnectionID}").
                First().
                Item("BEZEICHNUNG")

            Dim oIndex = cmbConnection.FindStringExact(oConnectionName)

            cmbConnection.SelectedIndex = oIndex
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try
    End Sub

    Private Sub LoadControls()
        Try
            Dim oDatatable = DATABASE_ECM.GetDatatable($"SELECT * FROM TBDD_INDEX_MAN WHERE DOK_ID = {DocTypeId} AND ACTIVE = 1")

            cmbControls.ValueMember = "WD_INDEX"
            cmbControls.DisplayMember = "NAME"
            cmbControls.DataSource = oDatatable
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Controls could not be loaded", MsgBoxStyle.Critical, Text)
        End Try
    End Sub

    Private Sub btnShowConnections_Click(sender As Object, e As EventArgs) Handles btnShowConnections.Click
        frmConnections.ShowDialog()
    End Sub


End Class