Imports System.Windows.Forms
Imports DD_LIB_Standards
Imports System.Data.SqlClient

Public Class frmWD_ChangeDoctype
    Private formloaded As Boolean = False
    Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
        Dim NewDoctype As String
        Dim DOCTYPE_ID
        Dim OBJECTTYPE As String
        Dim sql
        NewDoctype = cmbDokumentart.Text
        DOCTYPE_ID = cmbDokumentart.SelectedValue
        sql = "SELECT OBJEKTTYP FROM TBDD_DOKUMENTART WHERE GUID = " & DOCTYPE_ID
        OBJECTTYPE = clsDatabase.Execute_Scalar(sql, True)
        If OBJECTTYPE = String.Empty Then Me.Close()

        If NewDoctype = String.Empty Then
            MsgBox("Please choose a new doctype!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        sql = "Select IDXNAME_DOCTYPE from TBPMO_WD_OBJECTTYPE where Upper(object_type) = Upper('" & OBJECTTYPE & "')"
        Dim IDXNAME_DOCTYPE = clsDatabase.Execute_Scalar(sql, True)

        If Not IsNothing(IDXNAME_DOCTYPE) Then
            If Not IsNothing(CURRENT_TBPMO_INDEX_MAN) Then
                If CURRENT_TBPMO_INDEX_MAN.Rows.Count > 0 Then
                    If ClassFileResult.CheckWrite_IndexeMan(grbxControls) = False Then
                        Exit Sub
                    End If
                End If
            End If
            Me.DialogResult = System.Windows.Forms.DialogResult.OK
            For Each row As DataRow In CURRENT_DT_SELECTED_FILES.Rows
                sql = String.Format("UPDATE TBPMO_DOCRESULT_LIST SET Doctype = '{0}' WHERE DocID = {1}", NewDoctype, row.Item("DOC_ID"))
                If clsDatabase.Execute_non_Query(sql) = True Then
                    If LICENSE_SITE_PROXY = True And clsDatabase.DB_PROXY_INITIALIZED Then
                        clsDatabase.Execute_non_Query(sql, True)
                        sql = String.Format("UPDATE VWPMO_DOC_SEARCH SET Doctype = '{0}', Change_DateTime = GETDATE() WHERE DocID = {1}", NewDoctype, row.Item("DOC_ID"))
                        clsDatabase.Execute_non_Query(sql, True)
                    End If
                    If clsWD_SET.IndexFile(row.Item("FILEPATH"), IDXNAME_DOCTYPE, NewDoctype, OBJECTTYPE) = False Then
                        ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error while setting Doctype: ", "Check the logfile")
                    End If
                    If Not IsNothing(CURRENT_TBPMO_INDEX_MAN) Then
                        If CURRENT_TBPMO_INDEX_MAN.Rows.Count > 0 Then
                            ClassFileResult.DocID = row.Item("DOC_ID")
                            If ClassFileResult.Delete_Doc_Indices = True Then
                                ClassFileResult.SET_DOCID_INDICES()
                            End If

                        End If
                    End If
                End If
            Next
            Me.Close()
        End If
    End Sub

    Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
        Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub frmWDChangeDoctype_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            CURRENT_TBPMO_INDEX_MAN = Nothing
            CURRENT_DOKARTID = 0
            clsDatabase.GUI = True
            Dim sql = String.Format("SELECT T.GUID, dbo.FNPMO_GETOBJECTCAPTION('{0}', 'DOCTYPE_TITLE' + CONVERT(VARCHAR(5), T.GUID), 1) AS BEZEICHNUNG" & _
                                    " FROM TBDD_DOKUMENTART T, TBPMO_WD_FORMVIEW_DOKTYPES T1 WHERE T.GUID = T1.DOCTYPE_ID AND T.AKTIV = 1 AND T1.FORMVIEW_ID = {1} ORDER BY BEZEICHNUNG", USER_LANGUAGE, CURRENT_FORMVIEW_ID)
            Dim DT As DataTable = clsDatabase.Return_Datatable(sql, True)
            If Not IsNothing(DT) Then
                cmbDokumentart.DataSource = DT
                cmbDokumentart.DisplayMember = DT.Columns(1).ColumnName
                cmbDokumentart.ValueMember = DT.Columns(0).ColumnName
            End If

        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Load ChangeDoctype: ", ex.Message)
            Me.Close()
        End Try
    End Sub
    Sub Refresh_Indices_Manual()
        Try
            ClassFileResult.GET_DATATABLE_INDICES_PMO()
            If CURRENT_TBPMO_INDEX_MAN.Rows.Count > 0 Then
                'Der Tabelle eine Splate für den Indexwert hinzufügen
                Dim MAN_VALUE As DataColumn = CURRENT_TBPMO_INDEX_MAN.Columns.Add("MAN_VALUE", Type.GetType("System.String"))
                grbxControls.Visible = True
                grbxControls.Controls.Clear()
                Me.Size = New Size(430, 430)
                Dim anz As Integer = 1
                Dim ylbl As Integer = 20
                Dim y As Integer = 38

                For Each DR As DataRow In CURRENT_TBPMO_INDEX_MAN.Rows
                    Dim type = DR.Item("DATATYPE")
                    If type <> "BOOLEAN" Then
                        addLabel(DR.Item("GUID"), DR.Item("NAME"), DR.Item("COMMENT").ToString, ylbl)
                    End If
                    Dim DefaultValue = DR.Item("DEFAULT_VALUE")

                    Select Case type
                        Case "BOOLEAN"
                            Dim VORBELGUNG As Integer = DefaultValue
                            'nur eine Textbox
                            Dim chk As CheckBox = ClassControls_Manual.AddCheckBox(DR.Item("GUID"), DR.Item("NAME"), y, VORBELGUNG, DR.Item("COMMENT").ToString)
                            If Not IsNothing(chk) Then
                                grbxControls.Controls.Add(chk)
                            End If
                        Case "INTEGER"
                            If DR.Item("SUGGESTION") = True And DR.Item("SQL_RESULT").ToString.Length > 0 Then
                                AddVorschlag_ComboBox(DR.Item("GUID"), DR.Item("NAME"), y, DR.Item("CONNECTION_ID"), DR.Item("SQL_RESULT"), DefaultValue)
                                'AddAutoSuggest_Textbox(DR.Item("NAME"), y, DR.Item("CONNECTION_ID"), DR.Item("SQL_RESULT"), DefaultValue)
                            Else
                                Dim VORBELGUNG As Integer = DefaultValue
                                'nur eine Textbox
                                AddTextBox(DR.Item("GUID"), DR.Item("NAME"), y, VORBELGUNG)
                            End If
                        Case "VARCHAR"
                            If DR.Item("SUGGESTION") = True And DR.Item("SQL_RESULT").ToString.Length > 0 Then
                                AddVorschlag_ComboBox(DR.Item("GUID"), DR.Item("NAME"), y, DR.Item("CONNECTION_ID"), DR.Item("SQL_RESULT"), DefaultValue)
                                'AddAutoSuggest_Textbox(DR.Item("NAME"), y, DR.Item("CONNECTION_ID"), DR.Item("SQL_RESULT"), DefaultValue)
                            Else
                                If DR.Item("NAME").ToString.ToLower = "dateiname" Then
                                    'Übergibt den Dateinamen um diesen Vorzuschlagen
                                    AddTextBox(DR.Item("GUID"), DR.Item("NAME"), y, "")
                                Else
                                    Dim VORBELGUNG As String = DefaultValue
                                    'nur eine Textbox
                                    AddTextBox(DR.Item("GUID"), DR.Item("NAME"), y, VORBELGUNG)
                                End If
                            End If
                        Case "DATE"
                            AddDateTimePicker(DR.Item("GUID"), DR.Item("NAME"), y)
                        Case Else
                            MsgBox("Bitte überprüfen Sie den Datentyp des hinterlegten Indexwertes!", MsgBoxStyle.Critical, "Achtung:")
                            ClassLogger.Add(" - Datentyp nicht hinterlegt - LoadIndexe_Man")
                    End Select

                    anz += 1
                    ylbl += 45
                    y += 45
                Next
                SendKeys.Send("{TAB}")
            Else
                grbxControls.Visible = False
                Me.Size = New Size(430, 160)
            End If
        Catch ex As Exception
            MsgBox("Error in Refresh_Indices_Manual:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Sub addLabel(ID As Integer, indexname As String, hinweis As String, ylbl As Integer)
        Dim lbl As New Label
        lbl.Name = "lbl" & indexname
        lbl.Size = New Size(CInt(hinweis.Length * 15), 18) 'CInt(hinweis.Length * 9)
        lbl.Text = hinweis
        lbl.Tag = ID
        grbxControls.Controls.Add(lbl)
        lbl.Location = New Point(11, ylbl)
    End Sub
    Sub AddComboBoxValue(cmbName As ComboBox, Value As String)
        cmbName.Items.Add(Value)
    End Sub
    '    <STAThread()> _
    Function addCombobox(ID As Integer, indexname As String, y As Integer)
        Dim cmb As New ComboBox
        cmb.Name = "cmb" & indexname
        cmb.AutoSize = True
        cmb.Size = New Size(300, 27)
        cmb.Tag = ID
        grbxControls.Controls.Add(cmb)
        cmb.Location = New Point(11, y)
        'cmb.AutoCompleteMode = AutoCompleteMode.SuggestAppend
        'cmb.AutoCompleteSource = AutoCompleteSource.ListItems

        'AddHandler cmb.KeyUp, AddressOf AutoCompleteCombo_KeyUp
        AddHandler cmb.SelectedIndexChanged, AddressOf OncmbSIndexChanged
        AddHandler cmb.GotFocus, AddressOf OncmbGotFocus
        AddHandler cmb.LostFocus, AddressOf OncmbLostFocus
        Return cmb
    End Function
    Public Sub OncmbGotFocus(sender As System.Object, e As System.EventArgs)
        Dim cmb As ComboBox = sender
        cmb.BackColor = Color.Lime
    End Sub
    '    <STAThread()> _
    Public Sub OncmbLostFocus(sender As System.Object, e As System.EventArgs)
        Dim cmb As ComboBox = sender
        cmb.BackColor = Color.White
    End Sub
    Function AddTextBox(ID As Integer, indexname As String, y As Integer, text As String)
        Dim txt As New TextBox
        txt.Name = "txt" & indexname

        txt.Size = New Size(260, 27)
        'txt.AutoSize = True
        txt.Tag = ID
        grbxControls.Controls.Add(txt)
        txt.Location = New Point(11, y)

        If text <> "" Then
            txt.Text = text
            txt.Size = New Size(CInt(text.Length * 15), 27)
            txt.SelectAll()
        End If
        AddHandler txt.GotFocus, AddressOf OnTextBoxFocus
        AddHandler txt.LostFocus, AddressOf OnTextBoxLostFocus
        AddHandler txt.KeyUp, AddressOf OnTextBoxKeyUp
        AddHandler txt.TextChanged, AddressOf OnTextBoxTextChanged
        Return txt
    End Function
    Public Sub OnTextBoxFocus(sender As System.Object, e As System.EventArgs)
        Dim box As TextBox = sender
        box.BackColor = Color.Lime
        box.SelectAll()
    End Sub
    Public Sub OnTextBoxTextChanged(sender As System.Object, e As System.EventArgs)
        Dim box As TextBox = sender
        'If box.Text.Length > 15 Then
        Dim g As Graphics = box.CreateGraphics
        box.Width = g.MeasureString(box.Text, box.Font).Width + 15
        g.Dispose()
        ' End If

    End Sub

    Public Sub OnTextBoxLostFocus(sender As System.Object, e As System.EventArgs)
        Dim box As TextBox = sender
        box.BackColor = Color.White
    End Sub
    Public Sub OnTextBoxKeyUp(sender As System.Object, e As System.Windows.Forms.KeyEventArgs)
        Dim box As TextBox = sender
        If (e.KeyCode = Keys.Return) Then
            SendKeys.Send("{TAB}")
        End If
    End Sub
    Sub AddDateTimePicker(ID As Integer, indexname As String, y As Integer)
        Dim dtp As New DateTimePicker
        dtp.Name = "dtp" & indexname
        dtp.Format = DateTimePickerFormat.Short
        dtp.Size = New Size(133, 27)
        dtp.Tag = ID
        dtp.Location = New Point(11, y)
        grbxControls.Controls.Add(dtp)
        AddHandler dtp.ValueChanged, AddressOf OndtpChanged
    End Sub
    Sub OndtpChanged()
        'offen was hier zu tun ist
    End Sub
    Public Sub OncmbSIndexChanged(sender As System.Object, e As System.EventArgs)
        If formloaded = False Then
            Exit Sub
        End If

        Dim cmb As ComboBox = sender
        If cmb.SelectedIndex <> -1 Then
            If cmb.Text.Length > 15 Then
                Dim g As Graphics = cmb.CreateGraphics
                cmb.Width = g.MeasureString(cmb.Text, cmb.Font).Width + 30
                g.Dispose()
            End If
            Get_NextComboBoxResults(cmb)
            SendKeys.Send("{TAB}")
        End If
    End Sub
    Sub Get_NextComboBoxResults(cmb As ComboBox)
        Try
            Dim indexname = cmb.Name.Replace("cmb", "")
            Dim sql = "SELECT GUID,NAME,SQL_RESULT FROM TBPMO_INDEX_MAN where SUGGESTION = 1 AND SQL_RESULT like '%@" & indexname & "%' and DOCTYPE_ID = " & CURRENT_DOKARTID & " ORDER BY SEQUENCE"
            Dim DT As DataTable = clsDatabase.Return_Datatable(sql, True)
            If Not IsNothing(DT) Then
                If DT.Rows.Count > 0 Then
                    Dim cmbname = "cmb" & DT.Rows(0).Item("NAME")
                    Renew_ComboboxResults(DT.Rows(0).Item("GUID"), indexname, cmb.Text)
                End If

            End If
        Catch ex As Exception
            MsgBox("Error in Get_NextComboBoxResults:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub Renew_ComboboxResults(INDEX_GUID As Integer, SearchString As String, Resultvalue As String)
        Try

            Dim connectionString As String
            Dim sqlCnn As SqlConnection
            Dim sqlCmd As SqlCommand
            Dim adapter As New SqlDataAdapter

            Dim NewDataset As New DataSet
            Dim i As Integer

            'Dim DT_INDEX As DataTable = ClassDatabase.Return_Datatable("select * FROM TBPMO_INDEX_MAN WHERE GUID = " & INDEX_GUID, True)
            'If IsNothing(DT_INDEX) Then
            '    Exit Sub
            'End If

            Dim conid = ClassMoreMetadata.Return_CURRENT_TBPMO_INDEX_MAN_VALUE(INDEX_GUID, "CONNECTION_ID") ' DT_INDEX.Rows(0).Item("CONNECTION_ID")
            Dim sql_result = ClassMoreMetadata.Return_CURRENT_TBPMO_INDEX_MAN_VALUE(INDEX_GUID, "SQL_RESULT") 'DT_INDEX.Rows(0).Item("SQL_RESULT")
            Dim NAME = ClassMoreMetadata.Return_CURRENT_TBPMO_INDEX_MAN_VALUE(INDEX_GUID, "NAME") 'DT_INDEX.Rows(0).Item("NAME")
            If Not IsNothing(conid) And Not IsNothing(sql_result) And Not IsNothing(NAME) Then
                For Each ctrl As Control In Me.grbxControls.Controls
                    If ctrl.Name = "cmb" & NAME.ToString Then
                        Dim cmb As ComboBox = ctrl
                        Dim sql As String = sql_result.ToString.ToUpper.Replace("@" & SearchString.ToUpper, Resultvalue)

                        connectionString = ClassDatabase.GetConnectionString(conid)
                        If connectionString Is Nothing = False Then
                            'SQL Befehl füllt die Auswahlliste
                            If connectionString.Contains("Server=") And connectionString.Contains("Database=") Then
                                sqlCnn = New SqlConnection(connectionString)
                                sqlCnn.Open()
                                sqlCmd = New SqlCommand(sql, sqlCnn)
                                adapter.SelectCommand = sqlCmd
                                adapter.Fill(NewDataset)
                            ElseIf connectionString.StartsWith("Data Source=") And connectionString.Contains("SERVICE_NAME") Then
                                MsgBox("Oracle not yet implememnted!", MsgBoxStyle.Exclamation)
                                Exit Sub
                                'oracleConn = New OracleConnection(connectionString)
                                '' Try
                                'oracleConn.Open()
                                'oracleCmd = New OracleCommand(sql, oracleConn)
                                'oracleadapter.SelectCommand = oracleCmd
                                'oracleadapter.Fill(NewDataset)
                            End If
                            If NewDataset.Tables(0).Rows.Count > 0 Then
                                cmb.Items.Clear()
                                'Die Standargrösse definieren
                                Dim newWidth As Integer = 300
                                For i = 0 To NewDataset.Tables(0).Rows.Count - 1
                                    'MsgBox(NewDataset.Tables(0).Rows(i).Item(0))
                                    AddComboBoxValue(cmb, NewDataset.Tables(0).Rows(i).Item(0))
                                    Try
                                        Dim text As String = NewDataset.Tables(0).Rows(i).Item(0)
                                        If text.Length > 15 Then
                                            Dim g As Graphics = cmb.CreateGraphics
                                            If g.MeasureString(text, cmb.Font).Width + 30 > newWidth Then
                                                newWidth = g.MeasureString(text, cmb.Font).Width + 30
                                            End If
                                            g.Dispose()
                                        End If
                                    Catch ex As Exception
                                        MsgBox(ex.Message, MsgBoxStyle.Critical, "Unexpected error in Anpassung Breite ComboBox:")
                                    End Try

                                Next
                                cmb.Size = New Size(newWidth, 27)
                                cmb.AutoCompleteSource = AutoCompleteSource.ListItems
                                cmb.AutoCompleteMode = AutoCompleteMode.Suggest
                            End If
                            If connectionString.Contains("Server=") And connectionString.Contains("Database=") Then
                                Try
                                    adapter.Dispose()
                                    sqlCmd.Dispose()
                                    sqlCnn.Close()
                                Catch ex As Exception

                                End Try
                            Else
                                Try
                                    'oracleadapter.Dispose()
                                    'oracleCmd.Dispose()
                                    'oracleConn.Close()
                                Catch ex As Exception

                                End Try

                            End If

                        End If


                    End If
                Next
            End If
        Catch ex As Exception
            ClassLogger.Add(" - Unvorhergesehener Unexpected error in Renew_ComboboxResults - Fehler: " & vbNewLine & ex.Message)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Unvorhergesehener Unexpected error in Renew_ComboboxResults:")
        End Try
    End Sub
    Private Sub AddVorschlag_ComboBox(ID As Integer, indexname As String, y As Integer, conid As Integer, sql_Vorschlag As String, Optional Vorgabe As String = "")
        Try
            Dim connectionString As String
            Dim sqlCnn As SqlConnection
            Dim sqlCmd As SqlCommand
            Dim adapter As New SqlDataAdapter

            Dim NewDataset As New DataSet
            Dim i As Integer
            Dim sql As String
            Dim runinLZ As Boolean = False

            connectionString = ClassDatabase.GetConnectionString(conid)
            If connectionString Is Nothing = False Then
                'SQL Befehl füllt die Auswahlliste
                sql = sql_Vorschlag
                If Not sql.Contains("@") Then
                    If connectionString.Contains("Server=") And connectionString.Contains("Database=") Then
                        sqlCnn = New SqlConnection(connectionString)
                        sqlCnn.Open()
                        sqlCmd = New SqlCommand(sql, sqlCnn)
                        adapter.SelectCommand = sqlCmd
                        adapter.Fill(NewDataset)
                    ElseIf connectionString.StartsWith("Data Source=") And connectionString.Contains("SERVICE_NAME") Then
                        MsgBox("Oracle not yet implememnted!", MsgBoxStyle.Exclamation)
                        Exit Sub
                        'oracleConn = New OracleConnection(connectionString)
                        '' Try
                        'oracleConn.Open()
                        'oracleCmd = New OracleCommand(sql_Vorschlag, oracleConn)
                        'oracleadapter.SelectCommand = oracleCmd
                        'oracleadapter.Fill(NewDataset)
                    End If
                Else
                    runinLZ = True
                    If LogErrorsOnly = False Then ClassLogger.Add(" >>sql enthält Platzhalter und wird erst während der Laufzeit gefüllt!", False)
                End If



                Dim newCMB As ComboBox
                If runinLZ = True Then
                    'Die Standardcombobox anlegen
                    newCMB = addCombobox(ID, indexname, y)
                    newCMB.Size = New Size(300, 27)
                Else
                    If NewDataset.Tables(0).Rows.Count > 0 Then
                        'Die Standardcombobox anlegen
                        newCMB = addCombobox(ID, indexname, y)
                        'Die Standargrösse definieren
                        Dim newWidth As Integer = 300
                        For i = 0 To NewDataset.Tables(0).Rows.Count - 1
                            'MsgBox(NewDataset.Tables(0).Rows(i).Item(0))
                            AddComboBoxValue(newCMB, NewDataset.Tables(0).Rows(i).Item(0))
                            Try
                                Dim text As String = NewDataset.Tables(0).Rows(i).Item(0)
                                If text.Length > 15 Then
                                    Dim g As Graphics = newCMB.CreateGraphics
                                    If g.MeasureString(text, newCMB.Font).Width + 30 > newWidth Then
                                        newWidth = g.MeasureString(text, newCMB.Font).Width + 30
                                    End If
                                    g.Dispose()
                                End If
                            Catch ex As Exception
                                MsgBox(ex.Message, MsgBoxStyle.Critical, "Unexpected error in Anpassung Breite ComboBox:")
                            End Try

                        Next
                        newCMB.Size = New Size(newWidth, 27)
                        newCMB.AutoCompleteSource = AutoCompleteSource.ListItems
                        newCMB.AutoCompleteMode = AutoCompleteMode.Suggest
                        newCMB.DropDownHeight = (newCMB.ItemHeight + 0.2) * 25
                        If Vorgabe <> "" Then
                            newCMB.SelectedIndex = newCMB.FindStringExact(Vorgabe)
                            newCMB.Text = Vorgabe
                            Get_NextComboBoxResults(newCMB)
                        End If
                    Else

                    End If
                    If connectionString.Contains("Server=") And connectionString.Contains("Database=") Then
                        Try
                            adapter.Dispose()
                            sqlCmd.Dispose()
                            sqlCnn.Close()
                        Catch ex As Exception
                            MsgBox(ex.Message, MsgBoxStyle.Critical)
                        End Try
                    Else
                        Try
                            'oracleadapter.Dispose()
                            'oracleCmd.Dispose()
                            'oracleConn.Close()
                        Catch ex As Exception
                            MsgBox(ex.Message, MsgBoxStyle.Critical)
                        End Try

                    End If
                End If




            End If

        Catch ex As Exception
            ClassLogger.Add(" - Unvorhergesehener Unexpected error in AddVorschlag_ComboBox - Indexname: " & indexname & " - Fehler: " & vbNewLine & ex.Message)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Unvorhergesehener Unexpected error in AddVorschlag_ComboBox:")
        End Try
    End Sub

    Private Sub frmWD_ChangeDoctype_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        formloaded = True
    End Sub

    Private Sub cmbDokumentart_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbDokumentart.SelectedIndexChanged
        If cmbDokumentart.SelectedIndex <> -1 Then
            CURRENT_DOKARTID = 0
            Try
                CURRENT_DOKARTID = cmbDokumentart.SelectedValue
            Catch ex As Exception
                CURRENT_DOKARTID = 0
            End Try
            Refresh_Indices_Manual()
        End If
    End Sub
End Class
