Imports DD_Rights
Imports System.ComponentModel

Public Class frmUsersReworkRights
    Private _error As Boolean = False
    Private Sub frmCheckRightsEntity_Load(sender As Object, e As EventArgs) Handles Me.Load
        'lblstate.Visible = False
        Refresh_Users()
    End Sub
    Sub Refresh_Users()
        Try
            Dim Sql = String.Format("SELECT * FROM TBDD_USER WHERE MODULE_RECORD_ORG = 1 ORDER By USERNAME")
            Dim DT_USER = ClassDatabase.Return_Datatable(Sql)
            Try
                MyDataset.TBAD_Users.Clear()

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

                    newUserRow.ID = row.Item("GUID")
                    MyDataset.TBAD_Users.Rows.Add(newUserRow)
                    ' chklbxUserForGroup.Items.Add(New MyListBoxItem() With {.Text = row.Item(1), .ExtraData = row.Item(0)})
                Next
            Catch ex As Exception
                MsgBox("Error Load_Users for menues:" & vbNewLine & ex.Message)
            End Try
        Catch ex As Exception
            MsgBox("Unexpected error in load Users List: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub btnCheckRights_Click(sender As Object, e As EventArgs) Handles btnCheckRights.Click
        Dim Count As Integer
        For Each row As DataRow In MyDataset.TBAD_Users.Rows
            If row.Item(0) = CBool(True) Then
                Count += 1
            End If
        Next

        If Count > 0 Then
            Try
                Me.Cursor = Cursors.WaitCursor
                

               
                ''BackgroundWorker erstellen ...
                BW_RightsEntity = New BackgroundWorker
                BW_RightsEntity.WorkerReportsProgress = True
                'ProgressBar1.Maximum = Count + 1
                'lblstate.Visible = True
                'lblstate.Text = "Background Worker started...."
                ProgressPanel1.Description = "Preparing Right-Collector...."
                '  Me.ProgressBar1.Visible = True
                ProgressPanel1.Visible = True
                btnCheckRights.Enabled = False
                btncancel.Visible = True
                System.Threading.Thread.Sleep(500)
                Application.DoEvents()
                DO_Work()
                BW_RightsEntity_RunWorkerCompleted()
                'AddHandler BW_RightsEntity.DoWork, AddressOf bw_DoWork
                'BW_RightsEntity.ReportProgress(1)
                '.. und starten
                'BW_RightsEntity.RunWorkerAsync()
            Catch ex As Exception
                MsgBox("Unexpected error in starting backgroundworker: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                'Me.ProgressBar1.Visible = False
            End Try
        End If
        Me.Cursor = Cursors.Default

    End Sub

    Private Sub BW_RightsEntity_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BW_RightsEntity.ProgressChanged
        'Me.ProgressBar1.Value = e.ProgressPercentage
        ProgressPanel1.Description = "Collecting rights for user...."
    End Sub
    Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
        _error = False
        Dim i As Integer = 1
        For Each row As DataRow In MyDataset.TBAD_Users.Rows
            If row.Item(0) = CBool(True) Then
                ' ProgressPanel1.Description = "Collecting rights for user: " & row.Item("USERNAME")
                Dim sql = String.Format("DECLARE @return_value int " & vbNewLine & _
                   "EXEC	@return_value = [dbo].[PRPMO_RIGHTS_SERVICE_CHECK_USER] @USER_ID = {0}, @pCHECK_WHO = {1} " & vbNewLine & _
                   "SELECT	'Return Value' = @return_value", row.Item(5), Environment.UserName)
                Me.Cursor = Cursors.WaitCursor
                Dim DT As DataTable = ClassDatabase.Return_Datatable(sql)
                If Not IsNothing(DT) Then
                    Dim result = DT.Rows(0).Item(0)
                    If result <> 0 Then
                        MsgBox("Unexpected Error in Executing rightprocedure - Check the log!", MsgBoxStyle.Critical)
                        _error = True
                        BW_RightsEntity.ReportProgress(+1)
                        Exit For
                    Else
                        Dim del = String.Format("DELETE FROM TBPMO_USER_RIGHTS_JOBS WHERE USER_ID = {0}", row.Item(5))
                        ClassDatabase.Execute_non_Query(del)
                    End If
                End If

            End If
            BW_RightsEntity.ReportProgress(+1)
        Next
    End Sub
    Sub DO_Work()

        For Each row As DataRow In MyDataset.TBAD_Users.Rows
            If row.Item(0) = CBool(True) Then
                ProgressPanel1.Description = "Collecting rights for user...." & row.Item("USERNAME")
                Application.DoEvents()
                ' ProgressPanel1.Description = "Collecting rights for user: " & row.Item("USERNAME")
                Dim proc = String.Format("EXEC PRPMO_RIGHTS_SERVICE_CHECK_USER {0}, '{1}'", row.Item(5), Environment.UserName)
                If ClassDatabase.Execute_non_Query(proc, False, 240) = False Then
                    MsgBox("Unexpected Error in Executing rightprocedure - Check the log!", MsgBoxStyle.Critical)
                    _error = True
                    Exit For
                Else
                    Dim del = String.Format("DELETE FROM TBPMO_USER_RIGHTS_JOBS WHERE USER_ID = {0}", row.Item(5))
                    ClassDatabase.Execute_non_Query(del)
                End If
            End If
        Next
    End Sub
    Private Sub btncancel_Click(sender As Object, e As EventArgs) Handles btncancel.Click
        ' Cancel the asynchronous operation.
        Me.BW_RightsEntity.CancelAsync()
    End Sub

    Private Sub BW_RightsEntity_RunWorkerCompleted() '(sender As Object, e As RunWorkerCompletedEventArgs) 'Handles BW_RightsEntity.RunWorkerCompleted
        Try
            btncancel.Visible = False
            'ProgressBar1.Visible = False
            'lblstate.Visible = False
            btnCheckRights.Enabled = True
            btncancel.Visible = False
            ProgressPanel1.Visible = False
            If _error = False Then
                MsgBox("All rights of files belonging to User were checked and transmitted to the server!" & vbNewLine & "The setting of the rights might take up to 10 minutes!", MsgBoxStyle.Information)
            Else
                MsgBox("Some errors occured while checking and transmitting the rights...please check the log!", MsgBoxStyle.Exclamation)
            End If

        Catch ex As Exception
            btnCheckRights.Enabled = True
            btncancel.Visible = False
            ProgressPanel1.Visible = False
        End Try
    End Sub
End Class