Imports DevExpress.XtraTreeList
Public Class frmEntities
    Sub New()

        InitializeComponent()
    End Sub
    Private Shared _Instance As frmEntities = Nothing
    Private insert As Boolean = False
    Public Shared Function Instance() As frmEntities
        If _Instance Is Nothing OrElse _Instance.IsDisposed = True Then
            _Instance = New frmEntities
        End If
        _Instance.BringToFront()
        Return _Instance
    End Function

    Private Sub frmForm_Overview_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Try
            ClassWindowLocation.SaveFormLocationSize(Me, 1, CURRENT_SCREEN_ID, "frmForm_Overview")
            'Load_Forms()
            SaveLayout()
        Catch ex As Exception
            MsgBox("Error in Form Close:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub frmForm_Overview_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: Diese Codezeile lädt Daten in die Tabelle "DD_DMSDataSet.TBPMO_FORM_TYPE". Sie können sie bei Bedarf verschieben oder entfernen.

        Try
            TBPMO_FORMTableAdapter.Connection.ConnectionString = MyConnectionString
            TBPMO_FORM_VIEWTableAdapter.Connection.ConnectionString = MyConnectionString
            Me.TBPMO_FORM_TYPETableAdapter.Connection.ConnectionString = MyConnectionString
            Load_TreeView()
            Me.TBPMO_FORM_TYPETableAdapter.Fill(Me.DD_DMSDataSet.TBPMO_FORM_TYPE)
            ClassWindowLocation.LoadFormLocationSize(Me, 1, CURRENT_SCREEN_ID, "frmForm_Overview")


            LoadLayout()




        Catch ex As Exception
            MsgBox("Error in Form Load:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Sub Load_TreeView()
        Try

            Dim DT_SQL = String.Format("SELECT T.GUID, T1.FORM_TITLE,[dbo].[FNPMO_GETOBJECTCAPTION]('{0}','FORMVIEW_TITLE' + CONVERT(VARCHAR(5), T1.GUID), {1}) AS 'CAPTION' FROM " & _
                                       "TBPMO_FORM T, TBPMO_FORM_VIEW T1 WHERE T.GUID = T1.FORM_ID AND T.FORM_TYPE_ID = 1 AND T.PARENT_ID = 0 AND T.GUID IN (select DISTINCT ENTITY_ID FROM TBPMO_CLIENT_ENTITY WHERE CLIENT_ID IN (select client_Id from TBDD_CLIENT_USER where USER_ID = {2}))", USER_LANGUAGE, CURRENT_SCREEN_ID, USER_GUID)
            Dim DT As DataTable = ClassDatabase.Return_Datatable(DT_SQL)
            If DT.Rows.Count > 0 Then
                TreeViewEntity.Nodes.Clear()
                For Each Row As DataRow In DT.Rows
                    Dim Node As TreeNode
                    Node = TreeViewEntity.Nodes.Add(Row.Item("CAPTION").ToString)
                    Node.Tag = Row.Item("GUID")
                    Node.BackColor = Color.Orange
                    'Jetzt die Ebene1Knoten einhängen
                    DT_SQL = String.Format("SELECT T.GUID, T1.FORM_TITLE,[dbo].[FNPMO_GETOBJECTCAPTION]('{0}','FORMVIEW_TITLE' + CONVERT(VARCHAR(5), T1.GUID), {1}) AS 'CAPTION' FROM " & _
                                           "TBPMO_FORM T, TBPMO_FORM_VIEW T1 WHERE T.GUID = T1.FORM_ID AND T.FORM_TYPE_ID in (2,5) AND T.PARENT_ID = {2} AND T.GUID IN (select DISTINCT ENTITY_ID FROM TBPMO_CLIENT_ENTITY WHERE CLIENT_ID IN (select client_Id from TBDD_CLIENT_USER where USER_ID = {2})) ORDER BY LEVEL", USER_LANGUAGE, CURRENT_SCREEN_ID, Row.Item("GUID"), USER_GUID)
                    'Dim sql As String = "SELECT T.GUID, T1.FORM_TITLE FROM TBPMO_FORM T, TBPMO_FORM_VIEW T1 WHERE T.GUID = T1.FORM_ID AND T.FORM_TYPE_ID in (2,5) AND T.PARENT_ID = " & Row.Item("GUID") & " ORDER BY LEVEL"
                    Dim dtEbene1 As DataTable = ClassDatabase.Return_Datatable(DT_SQL)
                    If dtEbene1.Rows.Count > 0 Then
                        For Each row1 As DataRow In dtEbene1.Rows
                            Dim Node1 As TreeNode
                            Node1 = Node.Nodes.Add(row1.Item("CAPTION").ToString)
                            Node1.Tag = row1.Item("GUID")
                            DT_SQL = String.Format("SELECT T.GUID, T1.FORM_TITLE,[dbo].[FNPMO_GETOBJECTCAPTION]('{0}','FORMVIEW_TITLE' + CONVERT(VARCHAR(5), T1.GUID), {1}) AS 'CAPTION' FROM " & _
                                                   "TBPMO_FORM T, TBPMO_FORM_VIEW T1 WHERE T.GUID = T1.FORM_ID AND T.FORM_TYPE_ID in (3,5) AND T.PARENT_ID = {2} AND T.GUID IN (select DISTINCT ENTITY_ID FROM TBPMO_CLIENT_ENTITY WHERE CLIENT_ID IN (select client_Id from TBDD_CLIENT_USER where USER_ID = {3})) ORDER BY LEVEL", USER_LANGUAGE, CURRENT_SCREEN_ID, row1.Item("GUID"), USER_GUID)
                            ' Dim sql1 As String = "SELECT T.GUID, T1.FORM_TITLE FROM TBPMO_FORM T, TBPMO_FORM_VIEW T1 WHERE T.GUID = T1.FORM_ID AND T.FORM_TYPE_ID in (3,5) AND T.PARENT_ID = " & row1.Item("GUID") & " ORDER BY LEVEL"
                            'Jetzt die Ebene2 Knoten einhängen
                            Dim dtEbene2 As DataTable = ClassDatabase.Return_Datatable(DT_SQL)
                            If dtEbene2.Rows.Count > 0 Then
                                For Each row2 As DataRow In dtEbene2.Rows
                                    Dim Node2 As TreeNode
                                    Node2 = Node1.Nodes.Add(row2.Item("CAPTION").ToString)
                                    Node2.Tag = row2.Item("GUID")
                                Next
                            End If

                        Next

                    End If
                Next
                DT_SQL = String.Format("SELECT T.GUID, T1.FORM_TITLE,[dbo].[FNPMO_GETOBJECTCAPTION]('{0}','FORMVIEW_TITLE' + CONVERT(VARCHAR(5), T1.GUID), {1}) AS 'CAPTION' " & _
                                       "FROM TBPMO_FORM T, TBPMO_FORM_VIEW T1 WHERE T.GUID = T1.FORM_ID AND T.FORM_TYPE_ID = 4 AND T.PARENT_ID = 0 AND T.GUID IN (select DISTINCT ENTITY_ID FROM TBPMO_CLIENT_ENTITY WHERE CLIENT_ID IN (select client_Id from TBDD_CLIENT_USER where USER_ID = {2})) ORDER BY CAPTION", USER_LANGUAGE, CURRENT_SCREEN_ID, USER_GUID)
                'Dim sql2 As String = "SELECT T.GUID, T1.FORM_TITLE FROM TBPMO_FORM T, TBPMO_FORM_VIEW T1 WHERE T.GUID = T1.FORM_ID AND T.FORM_TYPE_ID = 4 AND T.PARENT_ID = 0 ORDER BY T1.FORM_TITLE"
                Dim DT3 As DataTable = ClassDatabase.Return_Datatable(DT_SQL)
                If DT3.Rows.Count > 0 Then
                    Dim Node As TreeNode
                    Node = TreeViewEntity.Nodes.Add("INDEPENDENT ENTITIES")
                    For Each row3 As DataRow In DT3.Rows
                        Dim Node2 As TreeNode
                        Node2 = Node.Nodes.Add(row3.Item("CAPTION").ToString)
                        Node2.Tag = row3.Item("GUID")
                    Next
                End If
                TreeViewEntity.ExpandAll()
                TreeViewEntity.Nodes(0).EnsureVisible()
            End If
        Catch ex As Exception
            MsgBox("Error in Load_TreeView:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Sub Load_Forms(FORMID As Object)
        Try
            FORMID = CInt(FORMID)
        Catch ex As Exception
            Exit Sub
        End Try
        Try

            Me.TBPMO_FORMTableAdapter.Fill(Me.DD_DMSDataSet.TBPMO_FORM, FORMID)
            Me.TBPMO_FORM_VIEWTableAdapter.FillByFORMID(Me.DD_DMSDataSet.TBPMO_FORM_VIEW, FORMID)

            Me.btnGenerate.Visible = True


            If PARENT_IDTextBox.Text = 0 And (ComboBox1.SelectedValue = 1 Or ComboBox1.SelectedValue = 4) Then
                Me.btnGenerate.Visible = True
            Else
                btnGenerate.Visible = False
            End If
        Catch ex As Exception
            MsgBox("Error in Load_Forms:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Open_Designer()
        Cursor = Cursors.WaitCursor
        OpenFormLevelDesigner()
        Cursor = Cursors.Default
    End Sub

    Sub Open_Viewer()
        Try
            If GUIDTextBox.Text = "" Then
                Exit Sub
            End If
            Dim FormId As Integer = GUIDTextBox.Text 'GetCurrentGUID()
            If FormId <> -1 Then
                Me.Hide()

                Cursor = Cursors.WaitCursor
                OpenFormInputFor(FormId, 1)
                Cursor = Cursors.Default
                ' Me.Visible = True
            End If
        Catch ex As Exception
            MsgBox("Error while Opening Entity View!" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        Try
            If GUIDTextBox.Text <> "" Then
                Dim FormId As Integer = GUIDTextBox.Text 'GetCurrentGUID()
                If FormId <> -1 Then
                    CURRENT_FORM_ID = FormId
                    Open_Designer()
                End If
            End If
        Catch ex As Exception
            MsgBox("Error while Opening Entity!" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click
        Open_Viewer()
    End Sub

    Private Sub gvMainView_DoubleClick(sender As Object, e As EventArgs)
        Open_Viewer()
    End Sub

    Private Function GetCurrentGUID() As Integer
        Dim FormId As Integer
        Try
            Dim CurrentRow As DataRowView = Me.TBPMO_FORMBindingSource.Current
            FormId = CurrentRow.Row.Item("GUID")
        Catch ex As Exception
            FormId = -1
        End Try

        Return FormId
    End Function

    Private Sub TBPMO_FORMBindingSource_AddingNew(sender As Object, e As System.ComponentModel.AddingNewEventArgs) Handles TBPMO_FORMBindingSource.AddingNew
        DD_DMSDataSet.TBPMO_FORM.ADDED_WHOColumn.DefaultValue = Environment.UserName
        DD_DMSDataSet.TBPMO_FORM_VIEW.ADDED_WHOColumn.DefaultValue = Environment.UserName
        DD_DMSDataSet.TBPMO_FORM.SHOW_FORM_CONSTRUCTColumn.DefaultValue = True
        DD_DMSDataSet.TBPMO_FORM.SINGLE_RECORDColumn.DefaultValue = False
        Me.GroupBox1.Visible = True
        insert = True
    End Sub
    Private Sub SaveLayout()
        Try
            Dim XMLPath = System.IO.Path.Combine(Application.UserAppDataPath(), "FORM-OVERVIEW-UserLayout.xml")
            ' treeListForms.SaveLayoutToXml(XMLPath)
        Catch ex As Exception
            MsgBox("Error while saving custom Layout!" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub LoadLayout()
        Try
            Dim XMLPath = System.IO.Path.Combine(Application.UserAppDataPath(), "FORM-OVERVIEW-UserLayout.xml")
            '  treeListForms.RestoreLayoutFromXml(XMLPath)
        Catch notFoundEx As System.IO.FileNotFoundException
            ClassLogger.Add("Layout added for Overview")
        Catch ex As Exception
            MsgBox("Error while loading custom Layout!" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
        Try
            If FORM_TITLETextBox.Text = "" Then
                MsgBox("Please insert a title for the entity! Will be displayed in Entity-hirarchy", MsgBoxStyle.Exclamation)
                FORM_TITLETextBox.Focus()
                Exit Sub
            End If
            If NAMETextBox.Text = "" Then
                MsgBox("Please isnert an internal name for the entity!", MsgBoxStyle.Exclamation)
                NAMETextBox.Focus()
                Exit Sub
            End If

            Dim FORM_TITLE As String = FORM_TITLETextBox.Text
            Dim DESCRIPTION As String = DESCRIPTIONTextBox.Text
            Me.TBPMO_FORMBindingSource.EndEdit()
            Dim changes = False

            ' Save FORM Properties
            If DD_DMSDataSet.TBPMO_FORM.GetChanges Is Nothing = False Then
                Me.CHANGED_WHOTextBoxPMOForm.Text = Environment.UserName
                Me.TBPMO_FORMBindingSource.EndEdit()
                Try
                    TBPMO_FORMTableAdapter.Update(DD_DMSDataSet.TBPMO_FORM)
                Catch ex As Exception
                    MsgBox("Error in Save/Insert Entity:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                    Exit Sub
                End Try
                changes = True
            End If

            ' Save FORM_VIEW Properties
            If insert = True Then
                Dim sql = "SELECT (MAX(GUID)) FROM TBPMO_FORM"
                Dim FORM_ID = ClassDatabase.Execute_Scalar(sql)

                Dim ADDED_WHO As String = Environment.UserName


                'MsgBox(FORM_TITLETextBox.Text)
                'ggg()
                If FORM_ID Is Nothing = False Then
                    sql = String.Format("INSERT INTO TBPMO_FORM_VIEW (FORM_ID, SCREEN_ID, FORM_TITLE, DESCRIPTION, ADDED_WHO,LANGUAGE) VALUES ({0}, {1},'{2}','{3}','{4}','{5}')", FORM_ID, CURRENT_SCREEN_ID, FORM_TITLE, DESCRIPTION, ADDED_WHO, USER_LANGUAGE)
                    ClassDatabase.Execute_non_Query(sql, True)
                End If
                Load_TreeView()
            Else
                Me.TBPMO_FORM_VIEWBindingSource.EndEdit()
                If DD_DMSDataSet.TBPMO_FORM_VIEW.GetChanges Is Nothing = False Then
                    Me.CHANGED_WHOTextBoxPMOFormView.Text = Environment.UserName
                    Me.TBPMO_FORM_VIEWBindingSource.EndEdit()
                    TBPMO_FORM_VIEWTableAdapter.Update(DD_DMSDataSet.TBPMO_FORM_VIEW)
                    changes = True
                End If
            End If
            insert = False
            If changes = True Then
                Load_TreeView()
                lblStatus.Text = "Changes successfully saved - " & Now
                lblStatus.Visible = True
                'MsgBox("Änderungen erfolgreich gespeichert!", MsgBoxStyle.Information)
            Else
                lblStatus.Visible = False
            End If
            ' Load_Forms()
        Catch ex As Exception
            MsgBox("Error in Entity:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub btndelete_Click(sender As Object, e As EventArgs) Handles btndelete.Click
        Dim result As MsgBoxResult = MsgBox("Wollen Sie das Formular wirklich löschen?" & vbNewLine & "Alle Daten werden unwiderruflich gelöscht!", MsgBoxStyle.YesNo, "Bestätigung notwendig:")
        If result = MsgBoxResult.Yes Then
            Try
                Dim CurrentID = GetCurrentGUID()
                Dim delete As String = "DELETE FROM TBPMO_FORM_SQL WHERE FORM_ID = " & CurrentID
                If ClassDatabase.Execute_non_Query(delete, True) = True Then
                    delete = "DELETE FROM TBPMO_FORM_SQL_CONSTRUCT WHERE FORM_ID = " & CurrentID
                    If ClassDatabase.Execute_non_Query(delete, True) = True Then
                        delete = "DELETE FROM TBPMO_WORKFLOW_ENTITY_STATE WHERE ENTITY_ID = " & CurrentID
                        If ClassDatabase.Execute_non_Query(delete, True) = True Then
                            delete = "DELETE FROM TBPMO_TEMPLATE_ENTITY WHERE ENTITY_ID = " & CurrentID
                            If ClassDatabase.Execute_non_Query(delete, True) = True Then
                                delete = "DELETE FROM TBPMO_FORM_CONSTRUCTOR_DETAIL WHERE FORM_ID = " & CurrentID
                                If ClassDatabase.Execute_non_Query(delete, True) = True Then
                                    ' Delete controls (and control screens and control values)
                                    If ClassFormCommands.DeleteFormControls(CurrentID) = True Then
                                        ' Delete form view
                                        If ClassFormCommands.DeleteFormView(CurrentID) = True Then
                                            delete = "DELETE FROM TBPMO_RECORD_CONNECT WHERE RECORD1_ID in (SELECT GUID FROM TBPMO_RECORD WHERE FORM_ID = " & CurrentID & ")"
                                            If ClassDatabase.Execute_non_Query(delete, True) = True Then
                                                delete = "DELETE FROM TBPMO_RECORD_CONNECT WHERE RECORD2_ID in (SELECT GUID FROM TBPMO_RECORD WHERE FORM_ID = " & CurrentID & ")"
                                                If ClassDatabase.Execute_non_Query(delete, True) = True Then
                                                    delete = "DELETE FROM TBPMO_RECORD_LOG WHERE RECORD_ID in (SELECT GUID FROM TBPMO_RECORD WHERE FORM_ID = " & CurrentID & ")"
                                                    If ClassDatabase.Execute_non_Query(delete, True) = True Then
                                                        delete = "DELETE FROM TBPMO_RECORD WHERE FORM_ID = " & CurrentID
                                                        If ClassDatabase.Execute_non_Query(delete, True) = True Then
                                                            ' Delete the actual form
                                                            Me.TBPMO_FORMTableAdapter.Delete(CurrentID)
                                                            MsgBox("Das Formular/Die Entität wurde erfolgreich gelöscht!", MsgBoxStyle.Information)
                                                            Load_TreeView()
                                                            Load_Forms(999999999)
                                                        End If

                                                    End If

                                                End If
                                            End If
                                        End If
                                    End If
                                End If
                            End If
                        End If


                    End If
                End If



            Catch ex As Exception
                MsgBox("Formular konnte nicht gelöscht werden:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            End Try
        End If
    End Sub

    Private Sub btninsert_Click(sender As Object, e As EventArgs) Handles btninsert.Click
        TBPMO_FORMBindingSource.AddNew()
    End Sub

    Private Sub TreeView1_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeViewEntity.AfterSelect
        Try
            If Not TreeViewEntity.SelectedNode Is Nothing Then
                Dim formId As Integer
                Try
                    formId = Integer.Parse(TreeViewEntity.SelectedNode.Tag)
                Catch ex As Exception
                    Exit Sub
                End Try

                Load_Forms(formId)
                TreeViewEntity.ExpandAll()
            End If
        Catch ex As Exception
            MsgBox("Error in AfterSelect:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub btncopy_Click(sender As Object, e As EventArgs) Handles btncopy.Click
        Dim result As MsgBoxResult = MsgBox("Wollen Sie diese Entität kopieren?", MsgBoxStyle.YesNo, "Frage:")
        If result = MsgBoxResult.Yes Then
            Try
                Dim CurrentID = GetCurrentGUID()
                Dim sql As String = "EXEC PRPMO_COPY_ENTITY " & CurrentID.ToString & ", '" & Environment.UserName & "'"
                If ClassDatabase.Execute_non_Query(sql) = True Then
                    'MsgBox("Die Entität wurde erfolgreich kopiert!", MsgBoxStyle.Information)
                    Load_TreeView()
                    Load_Forms(999999999)
                    lblStatus.Text = "Die Entität wurde erfolgreich kopiert."
                    lblStatus.Visible = True
                    MsgBox("Die Entität wurde erfolgreich kopiert!", MsgBoxStyle.Information)
                Else
                    lblStatus.Visible = False
                End If
            Catch ex As Exception
                MsgBox("Formular konnte nicht gelöscht werden:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            End Try
        End If

    End Sub

    Private Sub NAMETextBox_TextChanged(sender As Object, e As EventArgs) Handles NAMETextBox.TextChanged
        If insert = True Then
            FORM_TITLETextBox.Text = NAMETextBox.Text
        End If
    End Sub

    Private Sub btnGenerate_Click(sender As Object, e As EventArgs) Handles btnGenerate.Click
        Try
            Dim CurrentID = GetCurrentGUID()
            If CurrentID > 0 Then
                Dim result As MsgBoxResult = MsgBox("Achtung mit dieser Funktion wird ein NEUES Kombi-Formular erzeugt!" & vbNewLine & "Wollen Sie fortfahren?", MsgBoxStyle.YesNo, "Frage:")
                If result = MsgBoxResult.Yes Then
                    INTEGER1 = CurrentID
                    frmNewKombiForm.ShowDialog()
                End If
            End If


            'Dim CurrentID = GetCurrentGUID()
            'Dim sql As String = "EXEC PRPMO_COPY_ENTITY " & CurrentID.ToString
            'If ClassDatabase.Execute_non_Query(sql) = True Then
            '    'MsgBox("Die Entität wurde erfolgreich kopiert!", MsgBoxStyle.Information)
            '    Load_TreeView()
            '    Load_Forms(999999999)
            '    lblStatus.Text = "Die Entität wurde erfolgreich kopiert."
            '    lblStatus.Visible = True
            'Else
            '    lblStatus.Visible = False
            'End If
        Catch ex As Exception
            MsgBox("Formular konnte nicht gelöscht werden:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
        If ComboBox1.SelectedIndex <> -1 Then
            If ComboBox1.SelectedValue = 5 Then
                ToolStripButton2.Enabled = False
                ToolStripButton1.Enabled = False
            Else
                ToolStripButton2.Enabled = True
                ToolStripButton1.Enabled = True
            End If
        End If
    End Sub
End Class