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

    Private Sub Save_User_Rights_Data()
        Try
            Me.Validate()
            'Me.TBPMO_RIGHT_USERBindingSource.EndEdit()

            If DD_DMSDataSet.TBPMO_RIGHT_USER.GetChanges() Is Nothing = False Then
                'Me.TBPMO_RIGHT_USERDataGridView.CurrentRow.Cells("colADDED_WHO").Value = USER_USERNAME
                'Me.TBPMO_RIGHT_USERBindingSource.EndEdit()
                'Me.TBPMO_RIGHT_USERTableAdapter.Update(DD_DMSDataSet.TBPMO_RIGHT_USER)
                tschangedlabel.Text = "Right User changed - " & Now
                tschangedlabel.Visible = True
            Else
                tschangedlabel.Visible = False
            End If

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

    Private Sub Save_Group_Rights_Data()
        Try
            Me.Validate()
            Me.TBPMO_RIGHT_GROUPBindingSource.EndEdit()

            If DD_DMSDataSet.TBPMO_RIGHT_GROUP.GetChanges Is Nothing = False Then
                Try

                    Me.TBPMO_RIGHT_GROUPDataGridView.CurrentRow.Cells("DataGridViewTextBoxColumn6").Value = USER_USERNAME
                Catch ex As Exception

                End Try
                Me.TBPMO_RIGHT_GROUPBindingSource.EndEdit()
                Me.TBPMO_RIGHT_GROUPTableAdapter.Update(DD_DMSDataSet.TBPMO_RIGHT_GROUP)
                tschangedlabel.Text = "Right Group changed - " & Now
                tschangedlabel.Visible = True
            Else
                tschangedlabel.Visible = False
            End If

        Catch ex As Exception
            MsgBox("Error in Save_Group_Rights_Data:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_Datagrid(ByVal _Datagrid As DataGridView, ByVal _settings_String As String)
        Try
            Dim settings() As String
            If My.Settings(_settings_String) <> String.Empty Then
                settings = My.Settings(_settings_String).Split("$"c)
                For idx As Integer = 0 To _Datagrid.Columns.Count - 1
                    Dim sv() As String = settings(idx).Split("/"c)
                    _Datagrid.Columns(idx).DisplayIndex = CInt(sv(0))
                    _Datagrid.Columns(idx).Width = CInt(sv(1))
                Next
            End If
        Catch ex As Exception

        End Try
    End Sub
    Sub Save_Datagrid(ByVal _Datagrid As DataGridView, ByVal _settings_String As String)
        Try
            Dim settings As String = String.Empty
            For idx As Integer = 0 To _Datagrid.Columns.Count - 1
                settings += _Datagrid.Columns(idx).DisplayIndex.ToString()
                settings += "/"
                settings += _Datagrid.Columns(idx).Width.ToString
                settings += "$"
            Next
            My.Settings(_settings_String) = settings
        Catch ex As Exception
            My.Settings(_settings_String) = String.Empty
        End Try
    End Sub

    Private Sub frmRight_Management_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Save_Datagrid(TBPMO_RIGHT_GROUPDataGridView, "TBPMO_RIGHT_GROUPDataGridView")
        If LICENSE_PROXY = True And DD_LIB_Standards.clsDatabase.DB_PROXY_INITIALIZED Then
            MessageBox.Show("If You changed some data here, be aware that this data needs to be synchronized with Your proxy-data!" & vbNewLine & "The regualar processing-time are 30 minutes", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
        'Save_Datagrid(TBPMO_RIGHT_USERDataGridView, "TBPMO_RIGHT_USERDataGridView")
    End Sub
    Private Sub frmGroup_Rights_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: Diese Codezeile lädt Daten in die Tabelle "DD_ECMAdmin.TBDD_GROUPS". Sie können sie bei Bedarf verschieben oder entfernen.

        Refresh_Entities()
        Try
            Me.TBWH_USER_GROUPSTableAdapter.Connection.ConnectionString = MYDB_ECM.CurrentConnectionString
            Me.TBWH_USER_GROUPSTableAdapter.Fill(Me.DD_ECMAdmin.TBWH_USER_GROUPS)
            Me.TBDD_USER_GROUPSTableAdapter.Connection.ConnectionString = MYDB_ECM.CurrentConnectionString
            Me.TBDD_USER_GROUPSTableAdapter.Fill(Me.DD_DMSDataSet.TBDD_USER_GROUPS)
            Me.TBDD_GROUPSTableAdapter.Connection.ConnectionString = MYDB_ECM.CurrentConnectionString
            Me.TBDD_GROUPSTableAdapter.Fill(Me.DD_ECMAdmin.TBDD_GROUPS)
            Me.TBDD_USERTableAdapter.Connection.ConnectionString = MYDB_ECM.CurrentConnectionString
            Me.TBDD_USERTableAdapter.Fill(Me.DD_DMSDataSet.TBDD_USER)
        Catch ex As Exception
            MsgBox("Error in Loading Form:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
        Refresh_Rights_Groups()

        Load_Datagrid(TBPMO_RIGHT_GROUPDataGridView, "TBPMO_RIGHT_GROUPDataGridView")
        'Load_Datagrid(TBPMO_RIGHT_USERDataGridView, "TBPMO_RIGHT_USERDataGridView")
    End Sub

    Sub Refresh_Rights_Users(ENTITY_ID As Integer)
        Try
            USER_RIGHTSTableAdapter.Connection.ConnectionString = MYDB_ECM.CurrentConnectionString
            Me.USER_RIGHTSTableAdapter.Fill(Me.DD_ECMAdmin.USER_RIGHTS, USER_LANGUAGE, ENTITY_ID)
        Catch ex As Exception
            MsgBox("Error loading users:" & vbNewLine & ex.Message)
        End Try
    End Sub

    Sub Refresh_Rights_Groups()
        Try
            Me.TBPMO_RIGHT_GROUPTableAdapter.Connection.ConnectionString = MYDB_ECM.CurrentConnectionString
            Me.TBPMO_RIGHT_GROUPTableAdapter.Fill(Me.DD_DMSDataSet.TBPMO_RIGHT_GROUP)
        Catch ex As Exception
            MsgBox("Error in Refresh_Rights_Groups:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub Refresh_Entities()
        Try
            Me.TBWH_ENTITIESTableAdapter.Connection.ConnectionString = MYDB_ECM.CurrentConnectionString
            Me.TBWH_ENTITIESTableAdapter.Fill(Me.DD_ECMAdmin.TBWH_ENTITIES, USER_LANGUAGE, 1, USER_GUID)
        Catch ex As System.Exception
            MsgBox("Error in Refresh_Entities:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub TBPMO_RIGHT_GROUPBindingSource_AddingNew(sender As Object, e As System.ComponentModel.AddingNewEventArgs) Handles TBPMO_RIGHT_GROUPBindingSource.AddingNew
        Me.DD_DMSDataSet.TBPMO_RIGHT_GROUP.ADDED_WHOColumn.DefaultValue = USER_USERNAME
        Me.DD_DMSDataSet.TBPMO_RIGHT_GROUP.ENTITY_IDColumn.DefaultValue = MYDB_ECM.GetScalarValue("SELECT MIN(GUID) FROM TBPMO_FORM")
    End Sub
    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        Save_Group_Rights_Data()
    End Sub

    Private Sub TBPMO_RIGHT_GROUPBindingSource_CurrentChanged(sender As Object, e As EventArgs) Handles TBPMO_RIGHT_GROUPBindingSource.CurrentChanged
        tschangedlabel.Visible = False
    End Sub

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

    Private Sub ToolStripButton3_Click(sender As Object, e As EventArgs)
        Save_User_Rights_Data()
    End Sub

    Private Sub ToolStripButton4_Click(sender As Object, e As EventArgs) Handles ToolStripButton4.Click
        Refresh_Rights_Users(cmbEntity.SelectedValue)
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
        Select Case TabControl1.SelectedIndex
            Case 1
                Dim sql = String.Format("select T1.FORM_ID, [dbo].[FNPMO_GETOBJECTCAPTION]('{0}','FORMVIEW_TITLE' + CONVERT(VARCHAR(5), T1.GUID), 1) AS 'FORM_TITLE' FROM TBPMO_FORM_VIEW T1 " &
                                        "WHERE T1.SCREEN_ID = 1 ORDER BY T1.FORM_TITLE", USER_LANGUAGE)
                Dim DT As DataTable = MYDB_ECM.GetDatatable(sql)
                If Not IsNothing(DT) Then
                    cmbEntity.DataSource = DT
                    cmbEntity.DisplayMember = DT.Columns(1).ColumnName
                    cmbEntity.ValueMember = DT.Columns(0).ColumnName
                End If
                Refresh_Free_Users()
                Refresh_Rights_Users(cmbEntity.SelectedValue)
        End Select
    End Sub
    Sub Refresh_Free_Users()
        Dim Sql = $"SELECT T.* FROM TBDD_USER T INNER JOIN TBDD_USER_MODULES T1 ON T.GUID = T1.USER_ID INNER JOIN TBDD_MODULES T2 ON T1.MODULE_ID = T2.GUID 
WHERE T2.SHORT_NAME = 'ADDI'   AND T.GUID NOT IN (SELECT USER_ID FROM TBPMO_RIGHT_USER WHERE ENTITY_ID = {cmbEntity.SelectedValue}) ORDER BY USERNAME"
        Dim DT_USER = MYDB_ECM.GetDatatable(sql)
        Try
            DD_ECMAdmin.TBAD_Users.Clear()

            For Each row As DataRow In DT_USER.Rows
                Dim newUserRow As DD_ECMAdmin.TBAD_UsersRow
                newUserRow = DD_ECMAdmin.TBAD_Users.NewTBAD_UsersRow
                newUserRow.Username = row.Item("USERNAME")
                Try
                    newUserRow.Surname = row.Item("NAME")
                Catch ex As Exception
                    newUserRow.Surname = ""
                End Try
                Try
                    newUserRow.Prename = row.Item("PRENAME")
                Catch ex As Exception
                    newUserRow.Prename = ""
                End Try

                Try
                    newUserRow.Email = row.Item("EMAIL")
                Catch ex As Exception
                    newUserRow.Email = ""
                End Try

                newUserRow.ID = row.Item("GUID")
                DD_ECMAdmin.TBAD_Users.Rows.Add(newUserRow)
                ' chklbxUserForGroup.Items.Add(New MyListBoxItem() With {.Text = row.Item(1), .ExtraData = row.Item(0)})
            Next
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Error Refresh_Free_Users:", ex.Message)
        End Try

    End Sub

    Private Sub cmbEntity_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbEntity.SelectedIndexChanged
        If cmbEntity.SelectedIndex <> -1 Then
            Try
                Dim i As Integer = cmbEntity.SelectedValue
            Catch ex As Exception
                Exit Sub
            End Try
            Refresh_Free_Users()
            Refresh_Rights_Users(cmbEntity.SelectedValue)
        End If
    End Sub

    Private Sub btnAddUser2ConstructorREL_Click(sender As Object, e As EventArgs) Handles btnAddUser2ConstructorREL.Click
        Try
            Try
                Dim i As Integer = cmbEntity.SelectedValue
            Catch ex As Exception
                Exit Sub
            End Try
            For Each row As DataRow In DD_ECMAdmin.TBAD_Users.Rows
                If row.Item(0) = CBool(True) Then
                    Dim insert = String.Format("INSERT INTO TBPMO_RIGHT_USER (USER_ID,ENTITY_ID) VALUES ({0},{1})", row.Item(5), cmbEntity.SelectedValue)
                    If MYDB_ECM.ExecuteNonQuery(insert) = False Then
                        MsgBox("Could not insert the User-Definition....Check the logfile!", MsgBoxStyle.Exclamation)
                    End If
                End If
            Next
            For Each row As DataRow In DD_ECMAdmin.TBAD_Users.Rows
                row.Item(0) = CBool(False)
            Next
            Refresh_Free_Users()
            Refresh_Rights_Users(cmbEntity.SelectedValue)
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Error while adding user-rights:", ex.Message)
        End Try

    End Sub

    Private Sub btndeleteUserRight_Click(sender As Object, e As EventArgs) Handles btndeleteUserRight.Click
        Try
            Dim ID = GridView1.GetFocusedRowCellValue(GridView1.Columns("GUID"))
            Try
                Dim I As Integer = CInt(ID)
            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Error while deleting rights:", ex.Message)
                Exit Sub
            End Try
            Dim del = String.Format("DELETE FROM TBPMO_RIGHT_USER WHERE GUID = {0}", ID)
            If MYDB_ECM.ExecuteNonQuery(del) = True Then
                Refresh_Rights_Users(cmbEntity.SelectedValue)
                Refresh_Free_Users()
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected error in deleting rights:", ex.Message)
        End Try
    End Sub

    Private Sub GridView1_CellValueChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles GridView1.CellValueChanged
        Try
            GridView1.EndSelection()
            Dim column = e.Column.FieldName
            Dim ID = GridView1.GetFocusedRowCellValue(GridView1.Columns("GUID"))
            Try
                Dim I As Integer = CInt(ID)
            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Error getting row-ID:", ex.Message)
                Exit Sub
            End Try
            Dim int_bool As Integer
            If e.Value.ToString = "True" Then
                int_bool = 1
            Else
                int_bool = 0
            End If
            Dim upd = String.Format("UPDATE TBPMO_RIGHT_USER SET {0} = {1} WHERE GUID = {2}", column, int_bool, ID)
            If MYDB_ECM.ExecuteNonQuery(upd) = False Then
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Could not Update Right-details!")
                statelbl.Text = ""
            Else
                statelbl.Text = "ID: " & ID.ToString & " - '" & e.Column.Caption.ToString & "' updated. - " & Now.ToString
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in grvwGridPos_CellValueChanged: ", ex.Message)
        End Try
    End Sub

End Class