Imports DD_Rights
Imports System.ComponentModel

Public Class frmSupervisorEntity
    Private DT_FILES As DataTable
    Private _error As Boolean = False
    Private GUID_WORKING As Integer = 0
    Private CURR_ENTITY As Integer = 0
    Private countfiles As Integer = 0
    Private WorkingFiles As Integer = 0
    Private TYPE As String
    Private USER_ID As Integer
    Private Sub frmCheckRightsEntity_Load(sender As Object, e As EventArgs) Handles Me.Load
        lblstate.Visible = False
        Refresh_Combo()
    End Sub
    Sub Refresh_Combo()
        Try
            cmbUser.DataSource = Nothing
            cmbUser.DataSource = DT_WORK_USER_CONTROL_SUPERVISOR
            cmbUser.ValueMember = DT_WORK_USER_CONTROL_SUPERVISOR.Columns(0).ColumnName
            cmbUser.DisplayMember = DT_WORK_USER_CONTROL_SUPERVISOR.Columns(2).ColumnName
            If DT_WORK_USER_CONTROL_SUPERVISOR.Rows.Count = 0 Then
                MsgBox("No more Users to rework. Form will be closed!", MsgBoxStyle.Information)
                Me.Close()
            End If
        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 ECM_USER_ID As Integer
        If cmbUser.SelectedIndex <> -1 Then
            GUID_WORKING = 0
            Try
                If cmbUser.Text.Contains("SUPERVISOR DELETED") Then
                    TYPE = "SUPERVISOR DELETED"
                ElseIf cmbUser.Text.Contains("SUPERVISOR DELETED") Then
                    TYPE = "SUPERVISOR ADDED"
                Else
                    TYPE = ""
                End If
                USER_ID = 0
                Dim expression As String
                expression = "GUID = " & cmbUser.SelectedValue
                Dim foundRowsLevel0() As DataRow
                ' Use the Select method to find all rows matching the filter.
                foundRowsLevel0 = DT_WORK_USER_CONTROL_SUPERVISOR.Select(expression)
                Dim i As Integer
                Dim NODE_CONFIG_ID
                ' For each row
                For i = 0 To foundRowsLevel0.GetUpperBound(0)
                    USER_ID = foundRowsLevel0(i)("USER_ID")
                    CURR_ENTITY = foundRowsLevel0(i)("ENTITY_ID")
                Next
                Try
                    ECM_USER_ID = clsDatabase.Execute_Scalar(String.Format("SELECT USERID_FK_INT_ECM FROM TBDD_USER WHERE GUID = (SELECT USER_ID FROM TBPMO_USER_RIGHTS_JOBS WHERE GUID = {0} )", cmbUser.SelectedValue))
                Catch ex As Exception
                    MsgBox("No User ECM-ID found for selected User. Please inform Digital Data.", MsgBoxStyle.Exclamation)
                    Exit Sub
                End Try


                'Dim sql = String.Format("SELECT ENTITY_ID FROM VWPMO_WD_DOC_SEARCH where DocID in (SELECT [dwObjectID] FROM VWPMO_WD_OBJECT_RIGHTS  WHERE dwUserOrGroupID = {0}) GROUP BY ENTITY_ID", ECM_USER_ID)
                'Dim DT_ENTITY As DataTable = ClassDatabase.Return_Datatable(sql)
                'If DT_ENTITY.Rows.Count = 0 Then
                '    MsgBox("No files found for User. Job will be terminated!")
                '    Finish_Job()
                '    Exit Sub
                'End If


                Dim sql = String.Format("SELECT * FROM VWPMO_WD_DOC_SEARCH where DocID in (SELECT [dwObjectID] FROM VWPMO_WD_OBJECT_RIGHTS  WHERE dwUserOrGroupID = {0}) AND ENTITY_ID = {1}", ECM_USER_ID, CURR_ENTITY)
                DT_FILES = clsDatabase.Return_Datatable(sql)
                If DT_FILES.Rows.Count = 0 Then
                    MsgBox("No files found for User. Job will be terminated!")
                    Finish_Job()
                    Exit Sub
                End If
                If DD_Rights.ClassRights.Init(CURR_ENTITY, chklogging.Checked, DT_FILES.Rows.Count) = False Then
                    MsgBox("Could not init rights management. " & vbNewLine & "Check logfile", MsgBoxStyle.Critical)
                    Exit Sub
                End If
                'BackgroundWorker erstellen ...
                BW_RightsEntity = New BackgroundWorker
                BW_RightsEntity.WorkerReportsProgress = True
                ProgressBar1.Maximum = DT_FILES.Rows.Count
                countfiles = DT_FILES.Rows.Count
                WorkingFiles = 0
                lblstate.Visible = True
                lblstate.Text = "Starting Background Worker...."
                Me.ProgressBar1.Visible = True
                GUID_WORKING = cmbUser.SelectedValue
                AddHandler BW_RightsEntity.DoWork, AddressOf bw_DoWork

                '.. 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


    End Sub

    Private Sub BW_RightsEntity_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BW_RightsEntity.ProgressChanged
        Dim state = "Working on file '" & WorkingFiles.ToString & "' of '" & countfiles.ToString & "'"
        lblstate.Text = state
        Me.ProgressBar1.Value = e.ProgressPercentage
    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
        'Jede Datei einzeln verarbeiten
        For Each row As DataRow In DT_FILES.Rows
            If BW_RightsEntity.CancellationPending = True Then
                e.Cancel = True
                Exit For
            Else
                WorkingFiles += 1
                Select Case TYPE
                    Case "SUPERVISOR DELETED"
                        Dim AD_DOMAIN_USER = CStr(DD_Rights.ClassRights.AD_DOMAIN & "\" & Environment.UserName.ToUpper).ToUpper
                        If DD_Rights.ClassRights.File_DeleteRemoveRight(row.Item("DocID"), row.Item("FULL_FILENAME"), AD_DOMAIN_USER) Then
                            If DD_Rights.ClassRights.MSG_RESULT <> "" Then
                                MsgBox("Unexpected Errors in setting rights: " & vbNewLine & DD_Rights.ClassRights.MSG_RESULT, MsgBoxStyle.Exclamation)
                                _error = True
                            Else
                                If DD_Rights.ClassRights.Collect_MainUsers(row.Item("ENTITY_ID"), USER_ID, row.Item("RECORD_ID"), True) Then
                                    If ClassRights.DT_USER_RIGHT.Rows.Count > 0 Then
                                        clsLogger.Add(">> User owns rights for File/Record - right will be set!", False)
                                        If ClassRights.File_DeleteAndSetRight(row.Item("DocID"), row.Item("FULL_FILENAME"), False) Then

                                        End If
                                    End If

                                End If
                            End If
                        Else
                            clsLogger.Add(">> Unexpected Error in ClassRights.File_DeleteRemoveRight. Check Log.")
                            _error = True
                        End If
                    Case "SUPERVISOR ADDED"
                        MsgBox("Function actually not added!", MsgBoxStyle.Information)
                End Select
                

                If BW_RightsEntity.CancellationPending = False And BW_RightsEntity.IsBusy Then
                    BW_RightsEntity.ReportProgress(i)
                End If

                i += 1
            End If
        Next
        DD_Rights.ClassRights.Finalize_SettingRights()
    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
            If _error = False Then
               Finish_Job()
                MsgBox("All rights of files belonging to entity/User were checked and refreshed successfully!", MsgBoxStyle.Information)
            Else
                MsgBox("Some errors occured while checking and setting the rights...please check the log!" & vbNewLine & "Current Entity: " & CURR_ENTITY.ToString, MsgBoxStyle.Exclamation)
            End If
        Catch ex As Exception

        End Try
    End Sub
    Sub Finish_Job()
        Dim upd = String.Format("UPDATE TBPMO_USER_RIGHTS_JOBS SET WORKED = 1, CHANGED_WHO = 'JOB-RIGHTS FINISHER' WHERE GUID = {0}", GUID_WORKING)
        If clsDatabase.Execute_non_Query(upd) = True Then
            'Überprüfen ob es User gibt die aktualisiert werden müssen
            Dim Sql = SQL_USER_RIGHTS_CHANGED
            DT_WORK_USER_RIGHTS = clsDatabase.Return_Datatable(Sql)
            Refresh_Combo()
        End If
    End Sub
End Class