SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PrivateMessages_CreateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PrivateMessages_CreateDelete]
GO

CREATE  procedure [dbo].cs_PrivateMessages_CreateDelete
(
	@UserID int,
	@ThreadID int,
	@SettingsID int,
	@Action int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

IF (@Action = 0)
BEGIN
	-- Does the user already have the ability to see this thread?
	IF EXISTS (SELECT UserID FROM cs_PrivateMessages WHERE UserID = @UserID and ThreadID = @ThreadID and SettingsID = @SettingsID)
		RETURN
	
	INSERT INTO
		cs_PrivateMessages
	VALUES
	(
		@UserID,
		@ThreadID,
		@SettingsID
	)
	
	RETURN
END
	
IF (@Action = 2)
BEGIN
	-- This is a thread level delete operation ... and it works like this:
	-- as long as one of the pairs has the message in its list we don't want to delete 
	-- thread related data but only its link to that message. 
	
	-- The SectionID for any PM thread is 0
	DECLARE @SectionID INT
	SET @SectionID = 0
	 
	-- Delete user's link to this PM thread
	DELETE
		cs_PrivateMessages
	WHERE
		UserID = @UserID AND
		ThreadID = @ThreadID AND 
		SettingsID = @SettingsID
	
	-- Find out if there are any other pair that are bound to this PM thread.
	-- If no one is found then we may delete thread related data
	IF NOT EXISTS( SELECT UserID FROM cs_PrivateMessages WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID )
	BEGIN
		-- Delete thread related data
		EXEC cs_Thread_Delete @SettingsID, @SectionID, @ThreadID, 0, @UserID, ''
	END
END
	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_PrivateMessages_CreateDelete] to public
go