Imports DD_Rights
Imports System.ComponentModel
Imports DevExpress.XtraEditors.Repository
Imports DevExpress.Utils

Public Class frmCheckRightsRecords
    Private _formloaded As Boolean = False
    Private DT_FILES As DataTable
    Private _error As Boolean = False
    Private countfiles As Integer = 0
    Private WorkingFiles As Integer = 0
    Private CURR_DOCID As Integer
    Private CURR_DOCPATH As String
    Private ENTITY_ID As Integer
    Dim righterrors As Boolean = False
    Private DT_DATA As DataTable
    Private Sub frmCheckRightsRecords_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            Dim sql = String.Format("SELECT T.FORM_ID, [dbo].[FNPMO_GETOBJECTCAPTION]('{0}','FORMVIEW_TITLE' + CONVERT(VARCHAR(5), T.[FORM_VIEW_ID]), 1) AS FORM_TITLE FROM VWPMO_CONSTRUCTOR_FORMS T WHERE DOCUMENT_VIEW = 1", USER_LANGUAGE)
            Dim DT As DataTable = clsDatabase.Return_Datatable(sql)
            cmbentity.DataSource = DT
            cmbentity.ValueMember = DT.Columns(0).ColumnName
            cmbentity.DisplayMember = DT.Columns(1).ColumnName
            lblstate.Visible = False
        Catch ex As Exception
            MsgBox("Unexpected error in load form: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub btnCheckRights_Click(sender As Object, e As EventArgs) Handles btnCheckRights.Click
        If cmbentity.SelectedIndex <> -1 And DT_DATA.Rows.Count > 0 Then
            Try
                DT_DATA.AcceptChanges()

                righterrors = False
                CURR_DOCID = 0
                ENTITY_ID = cmbentity.SelectedValue
                countfiles = 0
                Me.ProgressBar1.Visible = True
                'BackgroundWorker erstellen ...
                BW_RightsEntity = New BackgroundWorker
                BW_RightsEntity.WorkerReportsProgress = True
                BW_RightsEntity.WorkerSupportsCancellation = True
                Dim listRecords As New ArrayList

                If DD_Rights.ClassWDRights.Init(chklogging.Checked, ClassDatabase.ConnectionStringRM) = False Then
                    MsgBox("Could not init rights management. " & vbNewLine & "Check logfile", MsgBoxStyle.Critical)
                    Exit Sub
                End If
                For Each row As DataRow In DT_DATA.Rows
                    If row.Item("Selection") = True Then
                        Dim recid = row.Item("Record-ID")
                        If Not IsNothing(recid) Then
                            listRecords.Add(recid)
                        End If
                    End If
                Next

                For Each Record As String In listRecords
                    Dim sqlfiles = String.Format("SELECT TRL.DOC_ID FROM TBPMO_DOC_RECORD_LINK TRL WHERE TRL.RECORD_ID = {0} ORDER BY TRL.DOC_ID", Record)
                    DT_FILES = clsDatabase.Return_Datatable(sqlfiles)
                    If DT_FILES.Rows.Count > 0 Then
                        countfiles += DT_FILES.Rows.Count
                    End If
                Next

                If countfiles = 0 Then
                    MsgBox("No files were found! Please check docsearch!", MsgBoxStyle.Critical)
                    Exit Sub
                Else
                    clsLogger.Add(String.Format(">> {0} files must be Checked!", countfiles), False)
                End If
                btncancel.Visible = True
                lblstate.Visible = True
                lblstate.Text = "Starting Background Worker...."
                WorkingFiles = 0
                ProgressBar1.Maximum = countfiles
                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
        Dim listRecords As New ArrayList
        For Each row As DataRow In DT_DATA.Rows
            If row.Item("Selection") = True Then
                Dim recid = row.Item("Record-ID")
                If Not IsNothing(recid) Then
                    listRecords.Add(recid)
                End If
            End If
        Next

        For Each Record As String In listRecords
            Dim sqlfiles = String.Format("SELECT T.DocID,T.FULL_FILENAME FROM VWPMO_DOC_SEARCH T, TBPMO_DOC_RECORD_LINK TRL where T.DocID = TRL.DOC_ID AND TRL.RECORD_ID = {0} ORDER BY DocID", Record)
            DT_FILES = clsDatabase.Return_Datatable(sqlfiles)
            If DT_FILES.Rows.Count > 0 Then
                For Each row As DataRow In DT_FILES.Rows
                    If BW_RightsEntity.CancellationPending = True Then
                        MsgBox("Backgroundworker aborting - check log!", MsgBoxStyle.Critical)
                        e.Cancel = True
                        Exit For
                    Else
                        '###
                        WorkingFiles += 1
                        CURR_DOCID = row.Item("DocID")
                        CURR_DOCPATH = row.Item("FULL_FILENAME")
                        If DD_Rights.ClassWDRights.Doc_Renew_Rights(CURR_DOCID, CURR_DOCPATH, True) Then
                            If DD_Rights.ClassWDRights.MSG_RESULT <> "" Then
                                righterrors = True
                            End If
                        Else
                            MsgBox("Unexpected Error in DD_Rights.ClassWDRights.Doc_Renew_Rights - Check the log!", MsgBoxStyle.Exclamation)
                            If DD_Rights.ClassWDRights.MSG_RESULT <> "" Then
                                MsgBox(DD_Rights.ClassWDRights.MSG_RESULT, MsgBoxStyle.Information)
                            End If
                            _error = True
                        End If
                        BW_RightsEntity.ReportProgress(i)
                        i += 1
                    End If
                Next
            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
            lblstate.Visible = False
            ProgressBar1.Visible = False
            If _error = False Then
                'clsDatabase.Execute_non_Query("UPDATE TBPMO_SERVICE_RIGHT_CONFIG SET RUN_SERVICE = 1 WHERE GUID = 1")
                If righterrors = True Then
                    MsgBox("All rights of files belonging to selected records were checked and refreshed, " & vbNewLine & "BUT some Userrights could not be set. Check the logfile!", MsgBoxStyle.Exclamation, "Attention")
                Else
                    MsgBox("All rights of files belonging to selected records were checked and refreshed!", MsgBoxStyle.Information)
                End If
            Else
                MsgBox("Some errors occured while preparing and queuing rights...please check the log!", MsgBoxStyle.Exclamation)
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub cmbentity_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbentity.SelectedIndexChanged
        Try
            If _formloaded = False Then Exit Sub

            If cmbentity.SelectedIndex <> -1 Then
                ENTITY_ID = cmbentity.SelectedValue
                Dim ViewName As String = "VWTEMP_PMO_FORM" & cmbentity.SelectedValue.ToString
                Dim EntitySQL As String = "SELECT CONVERT(BIT,0) as Selection, T.* FROM " & ViewName & " T where [file count] > 0"
                Me.Cursor = Cursors.WaitCursor
                DT_DATA = clsDatabase.Return_Datatable(EntitySQL)
                GridControlMain.DataSource = Nothing
                If GridViewMain.Columns.Count > 0 Then
                    GridViewMain.Columns.Clear()
                End If
                If Not IsNothing(DT_DATA) Then
                    GridControlMain.DataSource = DT_DATA
                    Dim checkboxEdit = New RepositoryItemCheckEdit()
                    Dim dateEdit As New RepositoryItemTimeEdit()
                    ' checkboxEdit vor-formatieren
                    checkboxEdit.ValueChecked = True
                    checkboxEdit.ValueUnchecked = False
                    ' dateEdit vor-formatieren
                    dateEdit.DisplayFormat.FormatType = FormatType.DateTime
                    dateEdit.Mask.UseMaskAsDisplayFormat = True
                    ' Editoren zum Grid hinzufügen
                    GridViewMain.GridControl.RepositoryItems.AddRange({checkboxEdit, dateEdit})
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        Finally
            Me.Cursor = Cursors.Default
        End Try




    End Sub

    Private Sub frmCheckRightsRecords_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        _formloaded = True
    End Sub

    Private Sub btnSelectVisiblRows_Click(sender As Object, e As EventArgs) Handles btnSelectVisiblRows.Click
        Dim listRecords As New ArrayList
        Dim collist As New ArrayList
        For i = 0 To GridViewMain.RowCount
            Dim recid = GridViewMain.GetRowCellValue(i, "Record-ID")
            If Not IsNothing(recid) Then
                listRecords.Add(recid)
            End If
        Next
        For Each row As DataRow In DT_DATA.Rows
            For Each Record As String In listRecords
                If Record = row.Item("Record-ID") Then
                    row.Item("Selection") = True
                    Exit For
                End If
            Next
        Next
    End Sub

    Private Sub btnUnselect_Click(sender As Object, e As EventArgs) Handles btnUnselect.Click
        Dim listRecords As New ArrayList
        Dim collist As New ArrayList
        For i = 0 To GridViewMain.RowCount
            Dim recid = GridViewMain.GetRowCellValue(i, "Record-ID")
            If Not IsNothing(recid) Then
                listRecords.Add(recid)
            End If
        Next
        For Each row As DataRow In DT_DATA.Rows
            For Each Record As String In listRecords
                If Record = row.Item("Record-ID") Then
                    row.Item("Selection") = False
                    Exit For
                End If
            Next
        Next
    End Sub

End Class