SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE           procedure [dbo].cs_nntp_Post_Add
(
	@NntpPostID 		int,
	@SectionID 		int,
	@NntpUniqueID 		nvarchar(256),
	@NntpParentUniqueID	nvarchar(245) = null,
	@UserName 		nvarchar(256),
	@Email	 		nvarchar(256),
	@Subject		nvarchar(256),
	@Body			ntext,
	@FormattedBody		ntext,
	@PostDate		datetime
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @ParentID int
DECLARE @PostID int
DECLARE @ThreadID int
DECLARE @UserID int
DECLARE @SettingsID int

SELECT @SettingsID = SettingsID FROM cs_Sections WHERE SectionID = @SectionID

-- Set the Parent ID to 0
SET @ParentID = 0

-- Attempt to find the user
SELECT @UserID = cs_UserID FROM cs_vw_Users_FullUser WHERE Email = @Email

-- Not linked via email
IF @UserID IS NULL
BEGIN
	-- Attempt to link via the username
	SELECT @UserID = cs_UserID FROM cs_vw_Users_FullUser WHERE UserName = @UserName

	-- Can't find the user
	IF @UserID IS NULL
	BEGIN

		EXEC cs_GetAnonymousUserID @SettingsID, @UserID output

	END
END

-- Already Added?
IF EXISTS (SELECT NntpPostID FROM cs_nntp_Posts WHERE NntpUniqueID = @NntpUniqueID)
	RETURN

-- Was a @NntpParentUniqueID specified?
IF @NntpParentUniqueID IS NOT NULL
BEGIN

	-- Attempt to find the ParentID of the Post
	SELECT 
		@ParentID = PostID
	FROM 
		cs_nntp_Posts 
	WHERE	
		NntpUniqueID = @NntpParentUniqueID

	IF @ParentID = 0
		RETURN
END

-- Insert the post into the cs_Posts table
exec cs_Post_CreateUpdate 
	@SectionID, 
	@ParentID, 
	1, 
	0,
	@Subject, 
	@UserID, 
	@UserName,
	@Body, 
	@FormattedBody, 
	0, 
	0, 
	0, 
	1,
	'1/1/1797', 
	0, 
	@PostDate, 
	'127.0.0.1', 
	null,
	null,
	@SettingsID,
	0,
	@PostID output,
	@ThreadID output

-- INSERT the post into the cs_nntp_Posts table
INSERT INTO
	cs_nntp_Posts
	(
		PostID,
		SectionID,
		NntpPostID,
		NntpUniqueID,
		SettingsID
	)
VALUES
	(
		@PostID,
		@SectionID,
		@NntpPostID,
		@NntpUniqueID,
		@SettingsID
	)

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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