Imports System.Data.SqlClient
Imports DD_LIB_Standards

Public Class ClassRecordCommands
    Public Shared Function CreateRecordProcedure(formId As Integer)
        Try
            Dim connection As New SqlConnection

            connection.ConnectionString = MYDB_ECM.CurrentConnectionString

            Using cmd As New SqlCommand("PRPMO_CREATE_RECORD", connection)

                cmd.CommandType = CommandType.StoredProcedure
                cmd.Parameters.AddWithValue("@pFORM_ID", formId)
                cmd.Parameters.AddWithValue("@pADDED_WHO", Environment.UserName)
                cmd.Parameters.Add("@pRESULT", SqlDbType.Int)
                cmd.Parameters("@pRESULT").Direction = ParameterDirection.Output

                connection.Open()
                cmd.ExecuteNonQuery()
                connection.Close()

                Dim GUID As Integer = cmd.Parameters("@pRESULT").Value
                If GUID > 0 And clsDatabase.DB_PROXY_INITIALIZED = True Then
                    If ClassProxy.PRPROXY_RECORD_UPD_INS(formId, GUID) = True Then
                        ClassProxy.PRPROXY_CONTROL_VALUE_RENEW(GUID)
                    End If

                End If
                Return GUID
            End Using
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in CreateRecordProcedure: ")
            LOGGER.Warn("Error in CreateRecordProcedure: " & ex.Message)
            ClassHelper.InsertEssential_Log(formId, "ENTITY-ID", "ENTITY-ID: " & formId & ": " & ex.Message)
            Return 0
        End Try
    End Function

    Public Shared Function CreateRecord(EntityID)
        Dim SQL = "INSERT INTO TBPMO_RECORD(ADDED_WHO, FORM_ID,RECORD_ENTITY_ID) VALUES ('" & USER_USERNAME & "', " & EntityID & ",4711)"
        Return MYDB_ECM.ExecuteNonQuery(Sql)
    End Function
    Public Shared Function GetLastRecord()
        Dim SQL = String.Format("SELECT MAX(GUID) FROM TBPMO_RECORD where PARENT_RECORD = 0 AND FORM_ID = {0} AND UPPER(ADDED_WHO) = UPPER('{1}') AND DELETED = 0", CURRENT_ENTITY_ID, USER_USERNAME)
        Return MYDB_ECM.GetScalarValue(SQL)
    End Function

    Public Shared Function ConnectRecord(PARENT_RECORD As Integer, LINK_RECORD As Integer, Optional Comment As String = "")
        Dim SQL = "INSERT INTO TBPMO_RECORD_CONNECT(RECORD1_ID,RECORD2_ID,COMMENT,ADDED_WHO) VALUES (" & PARENT_RECORD & "," & LINK_RECORD & ",'" & Comment & "','" & USER_USERNAME & "')"
        LOGGER.Debug("ConnectRecord SQL:  " & SQL)
        Return MYDB_ECM.ExecuteNonQuery(Sql)
    End Function
    Public Shared Function CHECK_RECORD_FINAL(RecordId As Integer, IsInsert As Boolean)
        If RecordId = 0 Then Return True
        Dim SQL = String.Format("EXEC PRPMO_RECORD_CHECK_INTEGRITY {0},'{1}',{2}", RecordId, Environment.UserName, IsInsert)
        Return MYDB_ECM.ExecuteNonQuery(Sql)
    End Function

End Class
