Imports DevExpress.Utils
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraGrid.Views.Grid
Imports DevExpress.XtraEditors
Imports DevExpress.XtraEditors.Repository

Public Class ClassWindreamDocGrid
    Public Shared SELECTED_DOC_PATH As String
    'Public Shared RESULT_OBJECTTYPE As String
    Public Shared SELECTED_INWORK As Boolean
    Public Shared SELECTED_DOC_ID As Integer
    'Public Shared RESULT_DISPLAYNAME As String
    Public Shared RESULT_CONFIG_IDS As Hashtable

    Public Shared DT_RESULTFILES As DataTable
    Private Shared DT_DROPDOWN_ITEMS As DataTable

    Private Shared _dropdownValueChangedHandler As EventHandler
    Private Shared _datepickerValueChangedHandler As EventHandler
    Private Shared _textValueChangedHandler As EventHandler
    Private Shared _checkValueChangedHandler As EventHandler

    Private Shared Function Init_Table()
        Try
            Dim table As New DataTable
            table.TableName = "TBSELECTED_FILES"
            ' Create two columns, ID and Name.
            table.Columns.Add("DOC_ID", GetType(Integer))
            table.Columns.Add("DOC_PATH", GetType(System.String))
            table.Columns.Add("OBJECTTYPE", GetType(System.String))
            table.Columns.Add("INWORK", GetType(System.Boolean))
            table.Columns.Add("DISPLAYNAME", GetType(System.String))
            DT_RESULTFILES = table
            Return True
        Catch ex As Exception
            ClassLogger.Add("Unexpected Error in Initting TableResult Docs: " & ex.Message, True)
            DT_RESULTFILES = Nothing
            Return False
        End Try
     
    End Function
    Public Shared Sub GetDocItems(gridView As GridView)
        If Init_Table() = True Then
            Console.WriteLine("gridView.SelectedRowsCount: " & gridView.SelectedRowsCount.ToString)
            If gridView.SelectedRowsCount > 1 Then
                DT_RESULTFILES.Clear()
                For Each row In gridView.GetSelectedRows
                    Dim newRow As DataRow = DT_RESULTFILES.NewRow()
                    Try

                        Dim DOC_ID = gridView.GetRowCellValue(row, "DocID")
                        SELECTED_DOC_ID = DOC_ID
                        newRow("DOC_ID") = gridView.GetRowCellValue(row, "DocID")
                    Catch ex As Exception
                        newRow("DOC_ID") = 0
                        SELECTED_DOC_ID = 0
                    End Try
                    Try
                        SELECTED_DOC_PATH = gridView.GetRowCellValue(row, "FULLPATH")
                        newRow("DOC_PATH") = gridView.GetRowCellValue(row, "FULLPATH")
                    Catch ex As Exception
                        newRow("DOC_PATH") = ""
                    End Try
                    Try
                        newRow("OBJECTTYPE") = gridView.GetRowCellValue(row, "OBJECTTYPE")
                    Catch ex As Exception
                        newRow("OBJECTTYPE") = ""
                    End Try
                    Try
                        newRow("INWORK") = gridView.GetRowCellValue(row, "in work?")
                        SELECTED_INWORK = gridView.GetRowCellValue(row, "in work?")
                    Catch ex As Exception
                        newRow("INWORK") = False
                        SELECTED_INWORK = False
                    End Try
                    Try
                        Dim dpn = gridView.GetRowCellValue(row, "Displayname")
                        If IsDBNull(dpn) Or IsNothing(dpn) Then
                            dpn = ""
                        End If
                        newRow("DISPLAYNAME") = dpn
                    Catch ex As Exception
                        newRow("DISPLAYNAME") = ""
                    End Try
                    DT_RESULTFILES.Rows.Add(newRow)
                    DT_RESULTFILES.AcceptChanges()
                Next
            Else
                Dim newRow As DataRow = DT_RESULTFILES.NewRow()
                Try
                    Dim DOC_ID = gridView.GetFocusedRowCellValue(gridView.Columns("DocID"))
                    SELECTED_DOC_ID = DOC_ID
                    newRow("DOC_ID") = gridView.GetFocusedRowCellValue(gridView.Columns("DocID"))
                Catch ex As Exception
                    newRow("DOC_ID") = 0
                    SELECTED_DOC_ID = 0
                End Try
                Try
                    SELECTED_DOC_PATH = gridView.GetFocusedRowCellValue(gridView.Columns("FULLPATH"))
                    newRow("DOC_PATH") = gridView.GetFocusedRowCellValue(gridView.Columns("FULLPATH"))
                Catch ex As Exception
                    newRow("DOC_PATH") = ""
                End Try
                Try
                    newRow("OBJECTTYPE") = gridView.GetFocusedRowCellValue(gridView.Columns("OBJECTTYPE"))
                Catch ex As Exception
                    newRow("OBJECTTYPE") = ""
                End Try
                Try
                    newRow("INWORK") = gridView.GetFocusedRowCellValue(gridView.Columns("in work?"))
                    SELECTED_INWORK = gridView.GetFocusedRowCellValue(gridView.Columns("in work?"))
                Catch ex As Exception
                    newRow("INWORK") = False
                    SELECTED_INWORK = False
                End Try
                Try
                    Dim dpn = gridView.GetFocusedRowCellValue(gridView.Columns("Displayname"))
                    If IsDBNull(dpn) Or IsNothing(dpn) Then
                        dpn = ""
                    End If
                    newRow("DISPLAYNAME") = dpn
                Catch ex As Exception
                    newRow("DISPLAYNAME") = ""
                End Try
                DT_RESULTFILES.Rows.Add(newRow)
                DT_RESULTFILES.AcceptChanges()
            End If
        End If
    End Sub

    Public Shared Sub FillColumns(gridView As GridView,
                                  DT_RESULT As DataTable, DT_WINDREAM_RESULTLIST As DataTable, DT_DOCRESULT_DROPDOWN_ITEMS As DataTable,
                                  DropdownValueChangedHandler As EventHandler, DatepickerValueChangedHandler As EventHandler, TextValueChangedHandler As EventHandler, CheckValueChangedHandler As EventHandler,
                                  SearchType As String, RECORD_ID As Integer)
        ' Handler speichern
        _dropdownValueChangedHandler = DropdownValueChangedHandler
        _datepickerValueChangedHandler = DatepickerValueChangedHandler
        _textValueChangedHandler = TextValueChangedHandler
        _checkValueChangedHandler = CheckValueChangedHandler

        'Dropdown Tabelle speichern
        DT_DROPDOWN_ITEMS = DT_DOCRESULT_DROPDOWN_ITEMS

        ' Tabelle vor dem verändern klonen
        Dim clonedTable As DataTable = DT_RESULT.Clone()

        RESULT_CONFIG_IDS = New Hashtable()

        ' Tabelle zurückspielen und zuweisen
        Try
            clonedTable.Load(DT_RESULT.CreateDataReader())
            DT_RESULT = clonedTable

            ' Neues Dataset für Master- und Detail-Tabelle erstellen
            Dim ds As New DataSet()

            '"FROM TBPMO_DOC_VALUES T INNER JOIN TBPMO_DOCSEARCH_RESULTLIST_CONFIG T1 ON T.CONFIG_ID = T1.GUID WHERE T1.ENTITY_ID = {0} AND T1.LANGUAGE = '{1}' AND T.RECORD_ID = {2} ORDER BY T.DocID, T1.SEQUENCE", CURRENT_ENTITY_ID, USER_LANGUAGE, RECORD_ID)
            Dim DT_DETAILS_SQL = String.Format("SELECT T.[GUID],T.[DocID],T.[CONFIG_ID],T1.HEADER_CAPTION,T.[VALUE],T1.[LANGUAGE], T1.COLUMN_VIEW,T1.EDITABLE,T1.TYPE_ID,T1.VISIBLE,T.CHANGED_WHEN,T.CHANGED_WHO " &
                                               "FROM TBPMO_DOC_VALUES T RIGHT JOIN TBPMO_DOCSEARCH_RESULTLIST_CONFIG T1 ON T.CONFIG_ID = T1.GUID WHERE T1.ENTITY_ID = {0} AND LANGUAGE = '{1}' AND T1.CONFIG_COLUMNS = 1", CURRENT_ENTITY_ID, USER_LANGUAGE)

            Dim DT_DETAILS As DataTable = ClassDatabase.Return_Datatable(DT_DETAILS_SQL, True)
            ' Tabellen zum DataSet hinzufügen
            ds.Tables.Add(DT_RESULT)
            ds.Tables.Add(DT_DETAILS)

            Dim resultTable As DataTable = ds.Tables(0)
            Dim detailsTable As DataTable = ds.Tables(1)

            ' Relation `docIdDetails` erstellen
            Dim parentColumn As DataColumn = resultTable.Columns("docId")
            Dim childColumn As DataColumn = detailsTable.Columns("docId")

            ' Unique Constraint für DT_RESULT auf Spalte `docId` erstellen
            Dim uniqueConstraint As UniqueConstraint = New UniqueConstraint(parentColumn)
            resultTable.Constraints.Add(uniqueConstraint)

            Try
                ' Parameter `createConstraints` auf false setzen, um erstellung eines unsinnigen
                ' `foreignKeyConstraints` zu verhindern
                ds.Relations.Add("docIdDetails", parentColumn, childColumn, False)
            Catch ex As Exception
                ClassLogger.Add(">> Could not set master-detail Relation DocSearch: " & ex.Message, False)
            End Try

            Dim gridControl As GridControl = gridView.GridControl


            ' Datasource auf Master-Tabelle setzen
            'gridView.GridControl.DataSource = DT_RESULT
            gridControl.DataSource = ds.Tables(0)
            gridControl.ForceInitialize()

            ' Detail View anlegen und der Relation `docIdDetails` zuweisen
            Dim grvwDetail As New GridView(gridControl)
            'grvwDetail.OptionsBehavior.Editable = False
            grvwDetail.OptionsView.ShowGroupPanel = False
            grvwDetail.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.Style3D
            grvwDetail.OptionsView.EnableAppearanceEvenRow = True
            grvwDetail.Appearance.EvenRow.BackColor = Color.Orange
            grvwDetail.Appearance.HeaderPanel.BackColor = Color.Orange
            grvwDetail.Appearance.HeaderPanel.Options.UseBackColor = True


            gridControl.LevelTree.Nodes.Add("docIdDetails", grvwDetail)
        Catch ex As Exception
            MsgBox("Error in FillColumns: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            ClassLogger.Add(">> Attention: Could not load converted datatable DocSearch: " & ex.Message, False)
        End Try

        AddHandler gridView.MasterRowExpanded, AddressOf gridView_MasterRowExpanded

        gridView.Columns.Item("ICON").MaxWidth = 24
        gridView.Columns.Item("ICON").MinWidth = 24
        gridView.Columns.Item("FULLPATH").Visible = False
        gridView.Columns.Item("OBJECTTYPE").Visible = False
        gridView.Columns.Item("DocID").Visible = False
        Dim created, changed As String
        If USER_LANGUAGE <> "de-DE" Then
            changed = "Changed"
            created = "Created"
        Else
            changed = "Geändert"
            created = "Erstellt"
        End If

        Dim createdColumn = gridView.Columns(created)
        If Not IsNothing(createdColumn) Then
            createdColumn.DisplayFormat.FormatType = FormatType.DateTime
            createdColumn.DisplayFormat.FormatString = CURRENT_DATE_FORMAT & " HH:MM:ss"
        End If

        Dim changedColumn = gridView.Columns(changed)
        If Not IsNothing(changedColumn) Then
            changedColumn.DisplayFormat.FormatType = FormatType.DateTime
            changedColumn.DisplayFormat.FormatString = CURRENT_DATE_FORMAT & " HH:MM:ss"
        End If

        ' Alle Spalten aus ReadOnly setzen, danach werden alle passenden auf nicht ReadOnly gesetzt
        For Each column As GridColumn In gridView.Columns
            column.OptionsColumn.AllowEdit = False
        Next
    End Sub

    Public Shared Sub detailView_CustomRowCellEdit(grvw As GridView, e As CustomRowCellEditEventArgs)
        If (e.Column.Name = "colVALUE") Then
            Dim rowView As DataRowView = grvw.GetRow(e.RowHandle)
            Dim configId As Integer = rowView.Item("CONFIG_ID")
            Dim title = rowView.Item("HEADER_CAPTION")
            Dim editable As Boolean = rowView.Item("EDITABLE")
            Dim typeId As Integer = rowView.Item("TYPE_ID")

            If typeId = 1 And editable Then
                Dim textedit As New RepositoryItemTextEdit()

                AddHandler textedit.Leave, _textValueChangedHandler

                e.RepositoryItem = textedit
            End If

            If typeId = 2 Then
                Dim checkEdit As New RepositoryItemCheckEdit()
                checkEdit.ValueChecked = "True"
                checkEdit.ValueUnchecked = "False"
                checkEdit.GlyphAlignment = HorzAlignment.Near
                checkEdit.Caption = String.Empty

                AddHandler checkEdit.CheckedChanged, _checkValueChangedHandler

                e.RepositoryItem = checkEdit
            End If

            If typeId = 3 Then
                Dim dateedit As New RepositoryItemDateEdit()

                AddHandler dateedit.EditValueChanged, _datepickerValueChangedHandler
                ' Brauchen wir Zeitangaben in den Custom Fields?
                'AddHandler dateedit.CustomDisplayText, Sub(sender As Object, _e As DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs)
                '                                           Dim value As String = _e.Value
                '                                           _e.DisplayText = value
                '                                           Dim parsedDate As DateTime = DateTime.ParseExact(value, "yyyy-MM-dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)

                '                                           _e.DisplayText = parsedDate.ToString(CURRENT_DATE_FORMAT & " HH:MM:ss")
                '                                       End Sub

                e.RepositoryItem = dateedit
            End If

            If typeId = 4 Then
                Dim dropdown As New RepositoryItemComboBox()
                Dim matchingRows() As DataRow = DT_DROPDOWN_ITEMS.Select(String.Format("CONFIG_ID = {0}", configId), "SEQUENCE")

                For Each matchingRow As DataRow In matchingRows
                    Dim item As New WindreamDocGridComboboxItem()
                    item.ConfigID = matchingRow.Item("CONFIG_ID")
                    item.Value = matchingRow.Item("VALUE")

                    dropdown.Items.Add(item)
                Next

                AddHandler dropdown.SelectedValueChanged, _dropdownValueChangedHandler

                e.RepositoryItem = dropdown

            End If
        ElseIf (e.Column.Name <> "colVALUE") Then
            ' Erlaube Editieren nur für VALUE Spalte
            e.Column.OptionsColumn.AllowEdit = False
        End If
    End Sub

    Public Shared Sub gridView_MasterRowExpanded(sender As GridView, e As DevExpress.XtraGrid.Views.Grid.CustomMasterRowEventArgs)
        Dim GW As GridView = sender

        Dim detailView As GridView = sender.GetDetailView(e.RowHandle, e.RelationIndex)
        With detailView.Columns
            'Spalten ausblenden
            .Item("GUID").Visible = False
            .Item("DocID").Visible = False
            .Item("CONFIG_ID").Visible = False
            .Item("LANGUAGE").Visible = False
            .Item("COLUMN_VIEW").Visible = False
            .Item("EDITABLE").Visible = False
            .Item("TYPE_ID").Visible = False
            .Item("VISIBLE").Visible = False

            'Spalten formatieren

            .Item("CHANGED_WHEN").DisplayFormat.FormatType = FormatType.DateTime
            .Item("CHANGED_WHEN").DisplayFormat.FormatString = CURRENT_DATE_FORMAT & " HH:MM:ss"

            If USER_LANGUAGE = "de-DE" Then
                .Item("HEADER_CAPTION").Caption = "Beschreibung"
                .Item("VALUE").Caption = "Wert"
                .Item("CHANGED_WHEN").Caption = "Geändert Wann"
                .Item("CHANGED_WHO").Caption = "Geändert Wer"
            Else
                .Item("HEADER_CAPTION").Caption = "Description"
                .Item("VALUE").Caption = "Value"
                .Item("CHANGED_WHEN").Caption = "Changed when"
                .Item("CHANGED_WHO").Caption = "changed Who"
            End If
        End With
        If Not IsNothing(GW.GridControl.ContextMenuStrip.Name) Then
            If GW.GridControl.ContextMenuStrip.Name = "cmsResultFilesBasic" Then
                detailView.OptionsBehavior.Editable = False
            Else
                detailView.OptionsBehavior.Editable = True
            End If
        End If
        AddHandler detailView.CustomRowCellEdit, AddressOf detailView_CustomRowCellEdit
    End Sub

    Public Class WindreamDocGridComboboxItem
        Implements IConvertible

        Public ConfigID As Integer
        Public Value As String

        Public Overrides Function ToString() As String
            Return Me.Value
        End Function

        Public Function ToString1(provider As IFormatProvider) As String Implements IConvertible.ToString
            Return Me.Value
        End Function

        Public Function GetTypeCode() As TypeCode Implements IConvertible.GetTypeCode
            Throw New NotImplementedException
        End Function

        Public Function ToBoolean(provider As IFormatProvider) As Boolean Implements IConvertible.ToBoolean
            Throw New NotImplementedException
        End Function

        Public Function ToByte(provider As IFormatProvider) As Byte Implements IConvertible.ToByte
            Throw New NotImplementedException
        End Function

        Public Function ToChar(provider As IFormatProvider) As Char Implements IConvertible.ToChar
            Throw New NotImplementedException
        End Function

        Public Function ToDateTime(provider As IFormatProvider) As Date Implements IConvertible.ToDateTime
            Throw New NotImplementedException
        End Function

        Public Function ToDecimal(provider As IFormatProvider) As Decimal Implements IConvertible.ToDecimal
            Throw New NotImplementedException
        End Function

        Public Function ToDouble(provider As IFormatProvider) As Double Implements IConvertible.ToDouble
            Throw New NotImplementedException
        End Function

        Public Function ToInt16(provider As IFormatProvider) As Short Implements IConvertible.ToInt16
            Throw New NotImplementedException
        End Function

        Public Function ToInt32(provider As IFormatProvider) As Integer Implements IConvertible.ToInt32
            Throw New NotImplementedException
        End Function

        Public Function ToInt64(provider As IFormatProvider) As Long Implements IConvertible.ToInt64
            Throw New NotImplementedException
        End Function

        Public Function ToSByte(provider As IFormatProvider) As SByte Implements IConvertible.ToSByte
            Throw New NotImplementedException
        End Function

        Public Function ToSingle(provider As IFormatProvider) As Single Implements IConvertible.ToSingle
            Throw New NotImplementedException
        End Function

        Public Function ToType(conversionType As Type, provider As IFormatProvider) As Object Implements IConvertible.ToType
            Throw New NotImplementedException
        End Function

        Public Function ToUInt16(provider As IFormatProvider) As UShort Implements IConvertible.ToUInt16
            Throw New NotImplementedException
        End Function

        Public Function ToUInt32(provider As IFormatProvider) As UInteger Implements IConvertible.ToUInt32
            Throw New NotImplementedException
        End Function

        Public Function ToUInt64(provider As IFormatProvider) As ULong Implements IConvertible.ToUInt64
            Throw New NotImplementedException
        End Function
    End Class

End Class
