
Imports DigitalData.GUIs.Common

Public Class frmColumn_Detail

    Private Class ComboboxItem
        Public Property Id As String
        Public Property Name As String

        Public Sub New(Id As String, name As String)

        End Sub
    End Class

    Private Sub frmControl_Detail_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            Me.TBPM_CONTROL_TABLETableAdapter.Connection.ConnectionString = CONNECTION_STRING_ECM
            If My.Settings.frmTableColumns_Position.IsEmpty = False Then
                If My.Settings.frmTableColumns_Position.X > 0 And My.Settings.frmTableColumns_Position.Y > 0 Then
                    Me.Location = My.Settings.frmTableColumns_Position
                End If
            End If

            SUMMARY_FUNCTIONCombobox.Properties.DataSource = New Dictionary(Of String, String) From {
                {ClassControlCreator.AGGREGATE_NONE, "Keine Summierung"},
                {ClassControlCreator.AGGREGATE_TOTAL_INTEGER, "Summe (Ganzzahl)"},
                {ClassControlCreator.AGGREGATE_TOTAL_FLOAT, "Summe (Zwei Nachkommastellen)"},
                {ClassControlCreator.AGGREGATE_TOTAL_CURRENCY, "Summe (Währung)"},
                {ClassControlCreator.AGGREGATE_TOTAL_COUNT, "Anzahl"},
                {ClassControlCreator.AGGREGATE_TOTAL_MIN, "Minimum"},
                {ClassControlCreator.AGGREGATE_TOTAL_MAX, "Maximum"},
                {ClassControlCreator.AGGREGATE_TOTAL_AVG, "Durchschnitt"}
            }

            TYPE_COLUMNComboBox2.Properties.DataSource = New Dictionary(Of String, String) From {
                {ClassControlCreator.CONTROL_TYPE_TEXT, "Text"},
                {ClassControlCreator.CONTROL_TYPE_BOOLEAN, "Boolean"},
                {ClassControlCreator.CONTROL_TYPE_INTEGER, "Ganzzahl"},
                {ClassControlCreator.CONTROL_TYPE_DOUBLE, "Fließkommazahl"},
                {ClassControlCreator.CONTROL_TYPE_CURRENCY, "Währung"}
            }
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Laden der Formulardaten:")
        End Try

    End Sub


    Private Sub TBPM_CONTROL_TABLEBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
        Me.Validate()
        Me.TBPM_CONTROL_TABLEBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DD_DMSLiteDataSet)

    End Sub

    Public Function FillData(ID As Integer)
        Try
            TBPM_CONTROL_TABLETableAdapter.Connection.ConnectionString = CONNECTION_STRING_ECM
            TBPM_CONTROL_TABLETableAdapter.FillByGUID(DD_DMSLiteDataSet.TBPM_CONTROL_TABLE, ID)
            Return True
        Catch ex As System.Exception
            MsgBox(TBPM_CONTROL_TABLETableAdapter.Connection.ConnectionString & vbNewLine & ex.Message, MsgBoxStyle.Critical, "Fehler beim Laden der Daten zu SpaltenID: " & ID)
        End Try

    End Function
    Private Sub READ_ONLYCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles READ_ONLYCheckBox.CheckedChanged
        Console.WriteLine($"READ_ONLY changed to: {READ_ONLYCheckBox.Checked}")
        Console.WriteLine($"CheckEditInheritValue is now: {CheckEditInheritValue.Checked}")
    End Sub

    Private Sub CheckEditInheritValue_CheckedChanged(sender As Object, e As EventArgs) Handles CheckEditInheritValue.CheckedChanged
        Console.WriteLine($"CheckEditInheritValue changed to: {CheckEditInheritValue.Checked}")
        Dim stackTrace As New StackTrace()
        Console.WriteLine($"Called from: {stackTrace}")
    End Sub

    Sub Save_Data()
        Try
            TBPM_CONTROL_TABLEBindingSource.EndEdit()
            If DD_DMSLiteDataSet.TBPM_CONTROL_TABLE.GetChanges Is Nothing = False Then
                Me.CHANGED_WHOTextBox.Text = USER_USERNAME
                TBPM_CONTROL_TABLEBindingSource.EndEdit()
                TBPM_CONTROL_TABLETableAdapter.cmdUpdate(
                    SPALTENNAMETextBox.Text,
                    SPALTEN_HEADERTextBox.Text,
                    SPALTENBREITETextBox.Text,
                    VALIDATIONCheckbox.Checked,
                    READ_ONLYCheckBox.Checked,
                    LOAD_IDX_VALUECheckBox.Checked,
                    CHANGED_WHOTextBox.Text,
                    REGEX_MATCHTextBox.Text,
                    REGEX_MESSAGE_DETextBox.Text,
                    REGEX_MESSAGE_DETextBox.Text,
                    DEFAULTVALUETextBox.Text,
                    SEQUENCETextBox.Text,
                    ADVANCED_LOOKUPCheckbox.Checked,
                    SUMMARY_FUNCTIONCombobox.EditValue,
                    TYPE_COLUMNComboBox2.EditValue,
                    LU_CAPTIONTextBox.Text,
                    CheckEditInheritValue.Checked,
                    FORMULA_EXPRESSIONTextBox.Text,
                    FORMULA_SQLTextBox.Text,
                    GUIDTextBox.Text
                )
                tslblAenderungen.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                tslblAenderungen.Caption = "Änderungen gespeichert - " & Now
                '  FillData(GUIDTextBox.Text)
            Else
                tslblAenderungen.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Speichern:")
        End Try
    End Sub

    Private Sub frmControl_Detail_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        My.Settings.frmTableColumns_Position = Me.Location
    End Sub



    Private Sub Button1_Click(sender As Object, e As EventArgs)
        Dim oForm As New frmRegexEditor()
        oForm.RegexString = REGEX_MATCHTextBox.Text

        Dim oResult = oForm.ShowDialog()
        If oResult = DialogResult.OK Then
            REGEX_MATCHTextBox.Text = oForm.RegexString
        End If
    End Sub

    Private Sub btnSQLEdit_Click(sender As Object, e As EventArgs)
        Dim oldSQL = SQL_COMMANDTextBox.Text
        CURRENT_DESIGN_TYPE = "SQL_SOURCE_TABLE_COLUMN"
        CURRENT_INDEX_ID = GUIDTextBox.Text
        Dim oForm2 As New frmSQLEditor(LOGCONFIG, DatabaseECM) With {
            .SQLCommand = SQL_COMMANDTextBox.Text,
            .SQLConnection = 1,
             .PlaceholdersManualPrefix = "CTRL",
             .PlaceholdersManualTitle = "Controls",
             .PlaceholdersManual = CURRENT_CONTROL_NAME_LIST.ToDictionary(Function(name) name, Function(name) name)
         }
        If IDB_ACTIVE = False Then
            oForm2.ATTRIBUTE_STORE = "WM"
            oForm2.PlaceholdersWindream = MVSource_AllIndicies
        Else
            oForm2.ATTRIBUTE_STORE = "IDB"
        End If
        oForm2.ShowDialog()

        If oForm2.DialogResult = DialogResult.OK Then
            If oldSQL <> oForm2.SQLCommand Then
                Dim oUpdate As String = $"Update TBPM_CONTROL_TABLE SET CHANGED_WHO = '{USER_USERNAME}', SQL_COMMAND = '{oForm2.SQLCommand.Replace("'", "''")}' 
                , CONNECTION_ID = {oForm2.SQLConnection} WHERE GUID = {GUIDTextBox.Text}"
                If DatabaseFallback.ExecuteNonQueryECM(oUpdate) = True Then
                    tslblAenderungen.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                    tslblAenderungen.Caption = "Changes saved - " & Now
                End If

            End If
        End If
    End Sub

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
        Save_Data()
    End Sub

    Private Sub BarButtonItem2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem2.ItemClick
        Try
            If MessageBox.Show("Wollen Sie diese Spalte wirklich löschen?", "Spalte löschen", MessageBoxButtons.YesNo) = DialogResult.Yes Then
                TBPM_CONTROL_TABLETableAdapter.Delete(GUIDTextBox.Text)
                Close()
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Löschen:")
        End Try
    End Sub

    Private Sub SimpleButton1_Click(sender As Object, e As EventArgs) Handles SimpleButton1.Click
        Dim oForm As New frmRegexEditor()
        oForm.RegexString = REGEX_MATCHTextBox.Text

        Dim oResult = oForm.ShowDialog()
        If oResult = DialogResult.OK Then
            REGEX_MATCHTextBox.Text = oForm.RegexString
        End If
    End Sub

    Private Sub SimpleButton2_Click(sender As Object, e As EventArgs) Handles SimpleButton2.Click
        Dim oldSQL = SQL_COMMANDTextBox.Text
        CURRENT_DESIGN_TYPE = "SQL_SOURCE_TABLE_COLUMN"
        CURRENT_INDEX_ID = GUIDTextBox.Text
        Dim oForm2 As New frmSQLEditor(LOGCONFIG, DatabaseECM) With {
            .SQLCommand = SQL_COMMANDTextBox.Text,
            .SQLConnection = 1,
             .PlaceholdersManualPrefix = "CTRL",
             .PlaceholdersManualTitle = "Controls",
             .PlaceholdersManual = CURRENT_CONTROL_NAME_LIST.ToDictionary(Function(name) name, Function(name) name)
         }
        If IDB_ACTIVE = False Then
            oForm2.ATTRIBUTE_STORE = "WM"
            oForm2.PlaceholdersWindream = MVSource_AllIndicies
        Else
            oForm2.ATTRIBUTE_STORE = "IDB"
        End If

        oForm2.ShowDialog()

        If oForm2.DialogResult = DialogResult.OK Then
            If oldSQL <> oForm2.SQLCommand Then
                Dim oUpdate As String = $"Update TBPM_CONTROL_TABLE SET CHANGED_WHO = '{USER_USERNAME}', SQL_COMMAND = '{oForm2.SQLCommand.Replace("'", "''")}' 
                , CONNECTION_ID = {oForm2.SQLConnection} WHERE GUID = {GUIDTextBox.Text}"
                If DatabaseFallback.ExecuteNonQueryECM(oUpdate) = True Then
                    tslblAenderungen.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                    tslblAenderungen.Caption = "Changes saved - " & Now
                    SQL_COMMANDTextBox.Text = oForm2.SQLCommand
                End If

            End If
        End If
    End Sub

    Private Sub RibbonControl1_Click(sender As Object, e As EventArgs) Handles RibbonControl1.Click

    End Sub

    Private Sub SimpleButton3_Click(sender As Object, e As EventArgs) Handles SimpleButton3.Click
        ' Alle verfügbaren Spalten für dieses Control laden
        Dim availableColumns As DataTable = GetAvailableColumnsForControl()

        ' Expression Designer öffnen
        Using designer As New frmExpression_Designer(availableColumns, FORMULA_EXPRESSIONTextBox.Text)
            If designer.ShowDialog() = DialogResult.OK Then
                FORMULA_EXPRESSIONTextBox.Text = designer.Expression
            End If
        End Using
    End Sub
    Private Function GetAvailableColumnsForControl() As DataTable
        ' Spalten aus der aktuellen Control-Definition laden
        Dim oSQL = "SELECT * FROM TBPM_CONTROL_TABLE WHERE CONTROL_ID  = " & CURRENT_CONTROL_ID & " ORDER BY SEQUENCE"
        Dim dt As DataTable = DatabaseFallback.GetDatatableECM(oSQL)
        Return dt
    End Function

    Private Sub SimpleButton4_Click(sender As Object, e As EventArgs) Handles SimpleButton4.Click
        Dim oldSQL = FORMULA_SQLTextBox.Text
        CURRENT_DESIGN_TYPE = "SQL_SOURCE_TABLE_COLUMN"
        CURRENT_INDEX_ID = GUIDTextBox.Text
        Dim oForm2 As New frmSQLEditor(LOGCONFIG, DatabaseECM) With {
            .SQLCommand = FORMULA_SQLTextBox.Text,
            .SQLConnection = 1,
            .PlaceholdersManualPrefix = "CTRL",
            .PlaceholdersManualTitle = "Controls",
            .PlaceholdersManual = CURRENT_CONTROL_NAME_LIST.ToDictionary(Function(name) name, Function(name) name)
         }
        If IDB_ACTIVE = False Then
            oForm2.ATTRIBUTE_STORE = "WM"
            oForm2.PlaceholdersWindream = MVSource_AllIndicies
        Else
            oForm2.ATTRIBUTE_STORE = "IDB"
        End If
        oForm2.ShowDialog()

        If oForm2.DialogResult = DialogResult.OK Then
            If oldSQL <> oForm2.SQLCommand Then
                Dim oUpdate As String = $"Update TBPM_CONTROL_TABLE SET CHANGED_WHO = '{USER_USERNAME}', FORMULA_SQL = '{oForm2.SQLCommand.Replace("'", "''")}' 
                , CONNECTION_ID = {oForm2.SQLConnection} WHERE GUID = {GUIDTextBox.Text}"
                If DatabaseFallback.ExecuteNonQueryECM(oUpdate) = True Then
                    tslblAenderungen.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                    tslblAenderungen.Caption = "Changes saved - " & Now
                    FORMULA_SQLTextBox.Text = oForm2.SQLCommand
                Else
                    MsgBox("Fehler beim Speichern des SQL Befehls. Bitte überprüfen Sie Ihre Eingabe und versuchen Sie es erneut.", MsgBoxStyle.Critical, "Fehler")
                End If

            End If
        End If
    End Sub

    Private Sub FORMULA_EXPRESSIONTextBox_TextChanged(sender As Object, e As EventArgs) Handles FORMULA_EXPRESSIONTextBox.TextChanged, FORMULA_SQLTextBox.TextChanged
        Dim oHasFormulaExpression As Boolean = FORMULA_EXPRESSIONTextBox.Text.Trim() <> String.Empty
        Dim oHasFormulaSql As Boolean = FORMULA_SQLTextBox.Text.Trim() <> String.Empty

        ' Entweder/Oder-Validierung: Beide gleichzeitig ist nicht erlaubt
        If oHasFormulaExpression AndAlso oHasFormulaSql Then
            MsgBox("Es darf nur FORMULA_EXPRESSION oder FORMULA_SQL gesetzt sein, nicht beides." & vbCrLf &
                   "Bitte leeren Sie eines der beiden Felder.",
                   MsgBoxStyle.Exclamation, "Ungültige Konfiguration")
        End If

        ' Wenn eine Formel gesetzt ist → ReadOnly aktivieren und sperren
        If oHasFormulaExpression OrElse oHasFormulaSql Then
            READ_ONLYCheckBox.Checked = True
            'READ_ONLYCheckBox.Enabled = False
        Else
            READ_ONLYCheckBox.Checked = False
        'READ_ONLYCheckBox.Enabled = True
        End If

    End Sub
End Class