SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROC [dbo].cs_Feed_GetFeedPosts
	@FeedId INT,
	@UserId INT,
	@SettingsID INT
AS

SELECT top 50 fp.FeedPostId,
	fp.FeedId,
	fp.Author,
	fp.Title,
	fp.Description,
	fp.Source,
	fp.GuidName,
	fp.GuidIsPermaLink,
	fp.Link,
	fp.PubDate,
	fp.CommentsUrl,
	fp.EnclosureUrl,
	fp.EnclosureLength,
	fp.EnclosureType,
	fp.Creator,
	fp.CommentApiUrl,
	fp.CommentRssUrl,
	fp.CommentCount, 
	HasRead = CASE WHEN urp.UserID 
			IS NULL THEN 0 ELSE 1 
		  END 
FROM 
	(SELECT DISTINCT UserID, FeedID FROM cs_FolderFeed) ff 
	INNER JOIN cs_Feed f ON
		ff.FeedId = f.FeedId
	INNER JOIN cs_FeedPost fp ON
		ff.FeedId = fp.FeedId
	LEFT OUTER JOIN cs_UserReadPost urp ON
		fp.FeedPostId	= urp.FeedPostId
	AND ff.UserID		= urp.UserID
WHERE
	ff.UserID = @UserId and f.SettingsID = @SettingsID
AND
  	ff.FeedId = @FeedId
ORDER BY fp.PubDate DESC


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_GetFeedPosts  TO PUBLIC
GO
