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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE        PROC [dbo].cs_RollerBlog_AddFeed
	@SectionID INT,
	@SettingsID INT,
	@FeedUrl NVARCHAR(512),
	@SiteUrl NVARCHAR(512),
    @Title NVARCHAR(512),
	@IntervalMin INT,
	@ExerptSize INT,
	@PostFullText BIT,
	@IsBlogAggregated BIT,
	@IsBlogRollAggregated BIT,
	@Enabled BIT,
	@State INT,
	@NewUrlID INT OUTPUT
AS

-- -- *** Test Data ***
-- DECLARE @SectionID INT
-- DECLARE @Url NVARCHAR(512)
-- DECLARE @Title NVARCHAR(512)
-- DECLARE @UrlId INT
-- 
-- SET @SectionID = 4 -- Sample Weblog
-- SET @Url = 'http://communityserver.org/roller/rss.ashx'
-- SET @Title = 'Community Server'
-- -- *** End Test Data ***

DECLARE @AUrlId INT
DECLARE @RecCount INT
DECLARE @CurrentDateTime DateTime
SET @CurrentDateTime = GetDate()

--Settings ID is now coming from the data layer
--DECLARE @SettingsID INT
--SET @SettingsID = (Select SettingsID FROM cs_Sections WHERE SectionID = @SectionID)

-- First, let's see if the url is already int cs_RollerBlogUrls.
SELECT @AUrlId = UrlID
FROM cs_RollerBlogUrls
WHERE Url = @FeedUrl --'http://communityserver.org/roller/rss.ashx'

-- If it's not, let's insert it and grab the FeedId.
IF (@AUrlId IS NULL)
  BEGIN
	
	-- Insert it.
	INSERT INTO cs_RollerBlogUrls
	(
		Url
	) 
	VALUES
	(
		@FeedUrl
	)

	-- Grab the identity generated.
	SELECT @AUrlId = @@IDENTITY

  END

-- Let's see if this feed is already part of cs_RollerBlogFeeds based on the SectionID and UrlId.
SET @RecCount = (SELECT COUNT(SectionID) FROM cs_RollerBlogFeeds WHERE UrlId = @AUrlId AND SectionID = @SectionID)

IF (@RecCount = 0)
BEGIN
        -- Add the feed to cs_RollerBlogFeeds based on SectionID (users blog).
	INSERT INTO cs_RollerBlogFeeds
	(
		SectionID,
		UrlId,
		SettingsId,
		SiteUrl,
        IntervalMinutes,
		Title,
		SubscribeDate,
		LastUpdateDate,
		LastModifiedDate,
		PostFullArticle,
		ExerptSize,
		IsBlogAggregated,
		IsBlogRollAggregated,
		Enabled,
		State
	)
	VALUES
	(
		@SectionID,
		@AUrlId,
		@SettingsID,
		@SiteUrl,
		@IntervalMin,
		@Title,
	    @CurrentDateTime,
	    @CurrentDateTime,
	    @CurrentDateTime,
		@PostFullText,
		@ExerptSize,
		@IsBlogAggregated,
		@IsBlogRollAggregated,
		@Enabled,
		@State
	)
END
ELSE
BEGIN
        -- Enable the already existing feed.
	UPDATE cs_RollerBlogFeeds
	SET 
		Enabled = 1, 
		IntervalMinutes = @IntervalMin, 
		Title = @Title,
		PostFullArticle = @PostFullText, 
		ExerptSize = @ExerptSize,
        IsBlogAggregated = @IsBlogAggregated, 
		IsBlogRollAggregated = @IsBlogRollAggregated, 
		SiteUrl = @SiteUrl
	WHERE UrlId = @AUrlId AND SectionID = @SectionID
END

SELECT @NewUrlID = @AUrlId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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