SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROC [dbo].cs_Folder_GetFeeds
	@UserId INT,
	@SettingsID int,
	@FolderId INT = NULL

AS


IF (@FolderId IS NULL)
  BEGIN

    SELECT  cf1.FeedId,
	    cf1.Url,
	    cf1.Title,
	    cf1.Link,
	    cf1.ETag,
	    cf1.LastModified,
	    cf1.Language,
	    cf1.Generator,
	    cf1.SubscribeDate,
	    cf1.LastUpdateDate,
	    cf1.FeedStateId,
	    cff.FolderFeedId
		,[UnreadCount] = ( select count(*) from (Select top 50 f.FeedPostID, f.FeedId FROM cs_FeedPost f where f.FeedId = cf1.FeedId order by PubDate DESC) fp left outer join cs_UserReadPost urp on fp.FeedPostID = urp.FeedPostID where fp.FeedId = cff.FeedId and urp.UserId IS NULL )
    FROM    cs_Feed AS cf1,
    	    cs_FolderFeed AS cff
    WHERE cff.FeedId = cf1.FeedId
      AND cff.UserId = @UserId
      AND cff.FolderId IS NULL 
      AND cf1.SettingsID = @SettingsID
    ORDER BY cf1.Title

  END

ELSE
  BEGIN

    SELECT  cf1.FeedId,
	    cf1.Url,
	    cf1.Title,
	    cf1.Link,
	    cf1.Language,
	    cf1.Generator,
	    cf1.ETag,
	    cf1.LastModified,
	    cf1.SubscribeDate,
	    cf1.LastUpdateDate,
	    cf1.FeedStateId,
	    cff.FolderFeedId
		,[UnreadCount] = ( select  count(*) from (Select top 50 f.FeedPostID, f.FeedId FROM cs_FeedPost f where f.FeedId = cf1.FeedId order by PubDate DESC) fp left outer join cs_UserReadPost urp on fp.FeedPostID = urp.FeedPostID where fp.FeedId = cff.FeedId and urp.UserId IS NULL )
    FROM    cs_Feed AS cf1,
    	    cs_FolderFeed AS cff
    WHERE cff.FeedId = cf1.FeedId
      AND cff.UserId = @UserId
      AND cff.FolderId = @FolderId 
      AND cf1.SettingsID = @SettingsID
    ORDER BY cf1.Title

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Folder_GetFeeds  TO PUBLIC
GO
