Imports System.Data.SqlClient
Imports DevExpress.Utils
Public Class ClassNodeNavigation
    Public Shared NODE_CONFIGURABLE_ID As Integer
    Public Shared MyTreeView As TreeView
    Public Shared Datatable_Nodes As DataTable
    Public Shared TREEVIEW_IMAGELIST As ImageList
    Public Shared IMAGE_COLLECTION As ImageCollection



    Public Shared Function CreateNodeProcedure(RECORD_ID As Integer, NODE_CONFIG_ID As Integer, NODE_CAPTION As String, NODE_ID1 As String, NODE_PARENT_ID As String, ADDED_WHO As String)
        Try
            Dim connection As New SqlConnection
            connection.ConnectionString = MYDB_ECM.CurrentConnectionString

            Using cmd As New SqlCommand("PRPMO_CREATE_NODE", connection)
                cmd.CommandType = CommandType.StoredProcedure
                '@pNODE_PARENT_ID INT, @pADDED_WHO 
                cmd.Parameters.AddWithValue("@pRECORD_ID", RECORD_ID)
                cmd.Parameters.AddWithValue("@pNODE_CONFIG_ID", NODE_CONFIG_ID)
                cmd.Parameters.AddWithValue("@pNODE_CAPTION", NODE_CAPTION)
                cmd.Parameters.AddWithValue("@pNODE_ID1", NODE_ID1)
                cmd.Parameters.AddWithValue("@pNODE_PARENT_ID", NODE_PARENT_ID)
                cmd.Parameters.AddWithValue("@pADDED_WHO", ADDED_WHO)
                cmd.Parameters.Add("@pRESULT", SqlDbType.Int)
                cmd.Parameters("@pRESULT").Direction = ParameterDirection.Output

                connection.Open()
                cmd.ExecuteNonQuery()
                connection.Close()

                Dim GUID As Integer = cmd.Parameters("@pRESULT").Value
                Return GUID
            End Using
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in CreateNodeProcedure: ")
            LOGGER.Warn("Error in CreateNodeProcedure: " & ex.Message)
            Return 0
        End Try
    End Function


    'Public Shared Function CREATE_IMAGE_COLL(DT_IMAGELIST As DataTable)
    '    IMAGE_COLLECTION = New ImageCollection
    '    For Each row As DataRow In DT_IMAGELIST.Rows
    '        Try
    '            Dim bimage = row.Item("NODE_IMAGE")
    '            If Not IsDBNull(bimage) Then
    '                Dim Node_image = ByteArrayToBitmap(bimage)
    '                IMAGE_COLLECTION.AddImage(Node_image, row.Item("GUID")) 'row.Item("GUID").ToString & "#" & row.Item("ENTITY_ID")

    '            End If
    '        Catch ex As Exception

    '        End Try

    '    Next
    'End Function


    'Public Shared Function Return_Node(PARENT_ID As Integer, ParentNode As TreeNode)
    '    Dim expression As String
    '    expression = "PARENT_GUID = " & PARENT_ID 'Einschränkung auf Type  und Parent_Guid
    '    Dim foundRows() As DataRow
    '    foundRows = Datatable_Nodes.Select(expression)
    '    Dim q As Integer
    '    For q = 0 To foundRows.GetUpperBound(0)
    '        Dim ID9 = foundRows(q)("GUID")
    '        Dim LevelEntity9 = foundRows(q)("ENTITY_ID")
    '        Dim controlID9 = foundRows(q)("CONTROL_ID")
    '        Dim nodetext9 = foundRows(q)("NODE_CAPTION")
    '        Dim RECORD_ID = foundRows(q)("RECORD_ID")
    '        Dim NODE_CONFIG_ID = foundRows(q)("NODE_CONFIG_ID")
    '        ' Node erstellen..
    '        Dim NEW_NODE As TreeNode
    '        NEW_NODE = New TreeNode(nodetext9)
    '        ClassNodeNavigation.Check_NODE_CONFIG_ID(LevelEntity9, NEW_NODE)
    '        NEW_NODE.Tag = ClassNodeNavigation.CreateNODE_TAG(LevelEntity9, ID9, RECORD_ID, NODE_CONFIG_ID)

    '        Dim index = 0
    '        For Each img As String In TREEVIEW_IMAGELIST.Images.Keys
    '            If img.Replace("LEVEL#ENTITY", "") = "6" & LevelEntity9.ToString Then
    '                Exit For
    '            End If
    '            index += 1
    '        Next
    '        NEW_NODE.ImageIndex = index
    '        NEW_NODE.SelectedImageIndex = index
    '        ' ..und einfügen
    '        ParentNode.Nodes.Add(NEW_NODE)
    '    Next '
    'End Function
    Public Shared Sub Check_NODE_CONFIG_ID(ENTITY_ID As Integer, myTreeNode As TreeNode)
        Try
            If myTreeNode Is Nothing Then
                Exit Sub
            End If
            Dim NODE_ID
            Dim NODE_CONFIG_ID
            Dim staticListItems = myTreeNode.Tag.Split("#")

            If staticListItems(0).Contains("NODE-TYPE") Or staticListItems(0).Contains("CONFIG_NODE") Then
                ' NODE_ID = staticListItems(0).ToString.Replace("NODE-TYPE-", "")
                NODE_ID = Return_NODEID_forTag(myTreeNode.Tag)
                NODE_CONFIG_ID = Return_NODE_CONFIG_ID_forTag(myTreeNode.Tag)

            Else
                LOGGER.Debug($"Attention no NODE-TYPE in staticListItems(0)  [{staticListItems(0).ToString}]")
            End If
            If NODE_CONFIGURABLE_NODES_DT.Rows.Count > 0 And IsNumeric(NODE_ID) Then
                'Prüfen ob es für dieses Level einen konfigurierbaren Knoten gibt
                Dim oTable As DataTable = NODE_CONFIGURABLE_NODES_DT
                ' Get rows with PARENT_ID = NODE_ID
                Dim result() As DataRow = oTable.Select("PARENT_NODE = " & NODE_CONFIG_ID)
                Dim count As Integer
                Dim ID
                ' Loop.

                For Each row As DataRow In result
                    count += 1
                    ID = row.Item("GUID")
                    CURRENT_NODE_IMAGE = row.Item("NODE_IMAGE")
                    If count = 2 Then Exit For
                Next

                'Dim result = (From form In NODE_CONFIGURABLE_NODES_DT.AsEnumerable()
                '              Select form
                '              Where form.Item("PARENT_NODE") = NODE_ID).Single()


                If Not IsNothing(ID) Then

                    ClassNodeNavigation.NODE_CONFIGURABLE_ID = ID
                    CURRENT_NODE_CONFIGURABLE_ID = ID
                Else
                    CURRENT_NODE_CONFIGURABLE_ID = 0
                End If
            Else


                CURRENT_NODE_CONFIGURABLE_ID = 0
            End If
        Catch ex As Exception
            LOGGER.Debug("SUB CNCID.CURRENT_NODE_CONFIGURABLE_ID would be nothing(1)...")
            ClassNodeNavigation.NODE_CONFIGURABLE_ID = 0
            CURRENT_NODE_CONFIGURABLE_ID = 0
        End Try

    End Sub
    Public Shared Function CreateNODE_TAG(Entity As Integer, IDNode As String, Record As Object, NODE_CONFIG_ID As Integer)
        Dim vType, TagString As String
        Try
            If NODE_CONFIGURABLE_ID = NODE_CONFIG_ID Then
                vType = "CONFIG_NODE-" & NODE_CONFIG_ID.ToString
            Else
                vType = "NODE-TYPE-" & NODE_CONFIG_ID.ToString
            End If
            If Not IsDBNull(Record) Then
                TagString = vType & "#" & Entity & "#NODE_ID-" & IDNode & "#RECORD-ID" & Record.ToString
            Else
                TagString = vType & "#" & Entity & "#NODE_ID-" & IDNode
            End If
            Return TagString
        Catch ex As Exception
            LOGGER.Warn("Unexpected Error in CreateNODE_TAG (NodeNavigation): " & ex.Message)
            MsgBox("Error in CreateNODE_TAG (NodeNavigation):" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            TagString = "ERROR NODETAG_CREATION"
            Return TagString
        End Try
    End Function
    Public Shared Function CreateTreeViewNodes(DT_TREEVIEW_NODES As DataTable, TREEVIEW_IMAGELIST As ImageList)
        Try
            LOGGER.Debug($"NODES: DT_TREEVIEW_NODES-Count: {DT_TREEVIEW_NODES.Rows.Count}")
            Dim sw As New SW("CreateTreeViewNodes")
            Dim mytrv As New TreeView
            Dim ENTITY_ID As Integer
            Dim expression As String
            expression = "PARENT_GUID = 0"
            Dim MAIN_NODES() As DataRow
            'Use the Select method to find all rows matching the filter.
            MAIN_NODES = DT_TREEVIEW_NODES.Select(expression, "SEQUENCE, NODE_CAPTION")
            ' For each row create a Node
            For i = 0 To MAIN_NODES.GetUpperBound(0)
                If ENTITY_ID <> MAIN_NODES(i)("ENTITY_ID") Then
                    ENTITY_ID = MAIN_NODES(i)("ENTITY_ID")
                    ClassNodeNavigation.Check_NODE_CONFIG_ID(MAIN_NODES(i)("ENTITY_ID"), Nothing)
                End If

                Dim NODE_Tag = CreateNODE_TAG(MAIN_NODES(i)("ENTITY_ID"), MAIN_NODES(i)("GUID"), MAIN_NODES(i)("RECORD_ID"), MAIN_NODES(i)("NODE_CONFIG_ID"))
                Dim MAIN_NODE = New TreeNode(MAIN_NODES(i)("NODE_CAPTION")) '"NODE_CAPTION"
                MAIN_NODE.Tag = NODE_Tag
                Dim index As Integer = 0
                For Each img As String In TREEVIEW_IMAGELIST.Images.Keys

                    If img = MAIN_NODES(i)("NODE_CONFIG_ID") Then ' & "#" & MAIN_NODES(i)("ENTITY_ID")
                        Exit For
                    End If
                    index += 1
                Next
                MAIN_NODE.ImageIndex = index
                MAIN_NODE.SelectedImageIndex = index
                'New Font(fontfamily, fontsize, CType(fontstyle, FontStyle))
                Dim fontfamily, backcolor As String
                Dim fontstyle, fontcolor, fontsize As Integer

                fontfamily = MAIN_NODES(i)("FONT_FAMILY").ToString
                fontsize = CInt(MAIN_NODES(i)("FONT_SIZE"))
                fontstyle = MAIN_NODES(i)("FONT_STYLE")
                fontcolor = MAIN_NODES(i)("FONT_COLOR")
                backcolor = MAIN_NODES(i)("BACK_COLOR")
                MAIN_NODE.NodeFont = New Font(fontfamily, fontsize, CType(fontstyle, FontStyle))
                MAIN_NODE.ForeColor = IntToColor(fontcolor)

                Try
                    If backcolor <> String.Empty Then
                        MAIN_NODE.BackColor = Color.FromName(backcolor)
                    End If

                Catch ex As Exception
                    LOGGER.Warn("Unexpected Error in Formatting NodeColor (CreateTreViewNodes): " & ex.Message)
                End Try


                MAIN_NODE = CheckSubNodes(DT_TREEVIEW_NODES, MAIN_NODES(i)("GUID"), TREEVIEW_IMAGELIST, MAIN_NODE, MAIN_NODES(i)("EXPAND_NODE"))
                'Add the node
                mytrv.Nodes.Add(MAIN_NODE)

            Next
            sw.Done()
            Return mytrv
        Catch ex As System.Exception
            LOGGER.Warn("Unexpected Error in CreateTreeViewNodes (NodeNavigation-CreateTreViewNodes): " & ex.Message)
            MsgBox("Error in CreateTreeViewNodes (NodeNavigation):" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return Nothing
        End Try
    End Function
    Private Shared Function CheckSubNodes(DT_TREEVIEW_NODES As DataTable, PARENT_GUID As Integer, TREEVIEW_IMAGELIST As ImageList, MY_NODE As TreeNode, EXPAND As Boolean)
        Dim ENTITY_ID As Integer
        Dim expression As String
        expression = "PARENT_GUID = " & PARENT_GUID.ToString
        Dim SUB_NODE_ROW() As DataRow
        ' Use the Select method to find all rows matching the filter.
        SUB_NODE_ROW = DT_TREEVIEW_NODES.Select(expression, "SEQUENCE, NODE_CAPTION")
        ' For each row create a Node
        For i = 0 To SUB_NODE_ROW.GetUpperBound(0)
            If ENTITY_ID <> SUB_NODE_ROW(i)("ENTITY_ID") Then
                ENTITY_ID = SUB_NODE_ROW(i)("ENTITY_ID")
                ClassNodeNavigation.Check_NODE_CONFIG_ID(SUB_NODE_ROW(i)("ENTITY_ID"), MY_NODE)
            End If
            Dim NODE_Tag = CreateNODE_TAG(SUB_NODE_ROW(i)("ENTITY_ID"), SUB_NODE_ROW(i)("GUID"), SUB_NODE_ROW(i)("RECORD_ID"), SUB_NODE_ROW(i)("NODE_CONFIG_ID"))
            If SUB_NODE_ROW(i)("NODE_CAPTION").ToString.Contains("Neuer") Then
                Console.WriteLine(SUB_NODE_ROW(i)("NODE_CAPTION"))
            End If
            Dim SUB_NODE = New TreeNode(SUB_NODE_ROW(i)("NODE_CAPTION"))
            SUB_NODE.Tag = NODE_Tag
            Dim index As Integer = 0
            For Each imgkey As String In TREEVIEW_IMAGELIST.Images.Keys
                If SUB_NODE_ROW(i)("NODE_CONFIG_ID") = "34" Then
                    Console.WriteLine(SUB_NODE_ROW(i)("NODE_CONFIG_ID"))

                End If
                Dim NODE_CONFIG_ID = SUB_NODE_ROW(i)("NODE_CONFIG_ID")

                If imgkey = SUB_NODE_ROW(i)("NODE_CONFIG_ID") Then '& "#" & SUB_NODE_ROW(i)("ENTITY_ID")
                    'found the key for this node
                    Exit For
                End If
                index += 1
            Next
            SUB_NODE.ImageIndex = index
            SUB_NODE.SelectedImageIndex = index
            Dim fontfamily, backcolor As String
            Dim fontstyle, fontcolor, fontsize As Integer

            fontfamily = SUB_NODE_ROW(i)("FONT_FAMILY").ToString
            fontsize = CInt(SUB_NODE_ROW(i)("FONT_SIZE"))
            fontstyle = SUB_NODE_ROW(i)("FONT_STYLE")
            fontcolor = SUB_NODE_ROW(i)("FONT_COLOR")
            backcolor = SUB_NODE_ROW(i)("BACK_COLOR")
            SUB_NODE.NodeFont = New Font(fontfamily, fontsize, CType(fontstyle, FontStyle))
            SUB_NODE.ForeColor = IntToColor(fontcolor)
            Try
                If backcolor <> String.Empty Then
                    SUB_NODE.BackColor = Color.FromName(backcolor)
                    Dim icolor = SUB_NODE.BackColor
                End If


            Catch ex As Exception
                LOGGER.Warn("Unexpected Error in Formatting NodeColor (Subnodes): " & ex.Message)
            End Try
            CheckSubNodes(DT_TREEVIEW_NODES, SUB_NODE_ROW(i)("GUID"), TREEVIEW_IMAGELIST, SUB_NODE, SUB_NODE_ROW(i)("EXPAND_NODE"))
            'Add the node
            MY_NODE.Nodes.Add(SUB_NODE)
            'If EXPAND = True Then
            '    MY_NODE.ExpandAll()
            'End If
        Next

        Return MY_NODE
    End Function

    Private Shared Function FindNode(tncoll As TreeNodeCollection, PARENT_GUID As Integer) As TreeNode
        Try
            Dim tnFound As TreeNode
            For Each tnCurr As TreeNode In tncoll
                If tnCurr.Tag.ToString.Contains("#NODE_ID-" & PARENT_GUID) Then
                    Return tnCurr
                End If
                tnFound = FindNode(tnCurr.Nodes, PARENT_GUID)
                If tnFound IsNot Nothing Then
                    Return tnFound
                End If
            Next
            Return Nothing
        Catch ex As Exception
            LOGGER.Warn("Unexpected Error in FindNode (NodeNavigation): " & ex.Message)
            MsgBox("Error in FindNode (NodeNavigation):" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return Nothing
        End Try

    End Function

    Public Shared Function Return_ENTITY_FOR_TAG(NodeString As String)

        If IsNumeric(NodeString) Then
            Return NodeString
        Else
            Try
                Dim staticListItems = NodeString.Split("#")
                Return staticListItems(1)
            Catch ex As Exception
                LOGGER.Warn("Unexpected Error in Return_ENTITY_FOR_TAG ('" & NodeString & "'): " & ex.Message)
                Return 0
            End Try
        End If
    End Function
    Public Shared Function Return_RECORD_forTag(NodeString As String)
        Dim sw As New SW("Return_RECORD_forTag")
        If IsNumeric(NodeString) Then
            Return NodeString
        Else
            Dim staticListItems = NodeString.Split("#")
            If staticListItems(3).Contains("RECORD-ID") Then
                Try
                    Dim _RECORD = staticListItems(3).ToString.Replace("RECORD-ID", "")
                    If IsNumeric(_RECORD) Then
                        sw.Done()
                        Return _RECORD
                    Else
                        sw.Done()
                        Return 0
                    End If
                Catch ex As Exception
                    sw.Done()
                    LOGGER.Warn("Unexpected Error in Return_RECORD_forTag ('" & NodeString & "'): " & ex.Message)
                    Return 0
                End Try
            Else
                sw.Done()
                Return 0
            End If

        End If
    End Function
    Public Shared Function Return_NODEID_forTag(NodeString As String)
        'If NODE_CONFIGURABLE_ID = NODE_CONFIG_ID Then
        '    vType = "CONFIG_NODE-" & NODE_CONFIG_ID.ToString
        'Else
        '    vType = "NODE-TYPE-" & NODE_CONFIG_ID.ToString
        'End If
        'If Not IsDBNull(Record) Then
        '    TagString = vType & "#" & Entity & "#" & "NODE_ID-" & IDNode & "#RECORD-ID" & Record.ToString
        'Else
        '    TagString = vType & "#" & Entity & "#" & "NODE_ID-" & IDNode
        'End If
        If IsNumeric(NodeString) Then
            Return NodeString
        Else
            Dim staticListItems = NodeString.Split("#")
            If staticListItems(2).Contains("NODE_ID") Then
                Return staticListItems(2).ToString.Replace("NODE_ID-", "")
            Else
                Return 0
            End If

        End If
    End Function
    Public Shared Function Return_NODE_CONFIG_ID_forTag(NodeString As String)
        'If NODE_CONFIGURABLE_ID = NODE_CONFIG_ID Then
        '    vType = "CONFIG_NODE-" & NODE_CONFIG_ID.ToString
        'Else
        '    vType = "NODE-TYPE-" & NODE_CONFIG_ID.ToString
        'End If
        'If Not IsDBNull(Record) Then
        '    TagString = vType & "#" & Entity & "#" & "NODE_ID-" & IDNode & "#RECORD-ID" & Record.ToString
        'Else
        '    TagString = vType & "#" & Entity & "#" & "NODE_ID-" & IDNode
        'End If
        'NODE-TYPE-17#5#NODE_ID-2
        If IsNumeric(NodeString) Then
            Return NodeString
        Else
            Dim staticListItems = NodeString.Split("#")
            If staticListItems(0).Contains("NODE-TYPE") Then
                Return staticListItems(0).ToString.Replace("NODE-TYPE-", "")
            ElseIf staticListItems(0).Contains("CONFIG_NODE") Then
                Return staticListItems(0).ToString.Replace("CONFIG_NODE-", "")
            Else
                Return 0
            End If

        End If
    End Function
End Class
