Public Class ClassRecordState

    Public Shared Sub LockRecord(RecordId As Integer)
        Try
            If RecordId = 0 Then
                Exit Sub
            End If
            Dim Username As String = USER_USERNAME
            Dim SQL As String = String.Format("UPDATE TBPMO_RECORD SET IN_WORK = 1, IN_WORK_WHO = '{0}' WHERE GUID = {1}", Username, RecordId)
            If DD_LIB_Standards.clsDatabase.DB_PROXY_INITIALIZED Then
                ClassDatabase.Execute_non_Query(SQL, True)
            End If
            ClassDatabase.Execute_non_Query(SQL)
        Catch ex As Exception
            MsgBox("Error in LockRecord: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Public Shared Sub UnlockRecord(RecordId As Integer)
        Try
            If RecordId = 0 Then
                Exit Sub
            End If
            Dim RECLOCKED = IsRecordLocked(RecordId)
            If IsNothing(RECLOCKED) Then
                Exit Sub
            End If
            Dim SQL As String = String.Format("UPDATE TBPMO_RECORD SET IN_WORK = 0, IN_WORK_WHO = NULL WHERE GUID = {0}", RecordId)
            If DD_LIB_Standards.clsDatabase.DB_PROXY_INITIALIZED Then
                ClassDatabase.Execute_non_Query(SQL, True)
            End If
            ClassDatabase.Execute_non_Query(SQL)
        Catch ex As Exception
            MsgBox("Error in UnlockRecord: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Public Shared Function IsRecordLocked(RecordId As Integer) As String
        Try
            Dim SQL As String = String.Format("SELECT IN_WORK, IN_WORK_WHO FROM TBPMO_RECORD WHERE GUID = {0}", RecordId)
            Dim dt As DataTable = ClassDatabase.Return_Datatable(SQL, True)

            If dt.Rows.Count = 1 Then

                Dim IN_WORK As Boolean = dt.Rows(0).Item("IN_WORK")
                Dim IN_WORK_WHO As String = dt.Rows(0).Item("IN_WORK_WHO").ToString

                If IN_WORK = True Then
                    ' Record ist in Arbeit, benutzer zurückgeben
                    Return IN_WORK_WHO
                ElseIf IN_WORK = False Then
                    ' Record ist nicht in Arbeit, nothing zurück geben
                    Return Nothing
                End If

            ElseIf dt.Rows.Count = 0 Then
                Return Nothing
            Else
                Throw New Exception("Record" & RecordId & " is not unique")
            End If
        Catch ex As Exception
            MsgBox("Error in IsRecordInWork: " + vbNewLine + ex.Message, MsgBoxStyle.Critical)
            Return Nothing
        End Try
    End Function

End Class
