SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE dbo.cs_Favorite_Add
(
	@SettingsID			int,
	@UserID				int,
	@ItemID				int,
	@FavoriteType		int,
	@ApplicationType	int,
	@FavoriteID			int OUTPUT
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	IF @FavoriteType = 1		-- Section
	BEGIN

		-- Check if favorite already exists, return existing id
		SELECT	@FavoriteID = F.FavoriteID
		FROM	cs_FavoriteSections F
		WHERE	OwnerID = @UserID
			AND	SettingsID = @SettingsID
			AND	SectionID = @ItemID
			AND	ApplicationType = @ApplicationType

		-- New favorite
		IF @FavoriteID IS NULL
		BEGIN

			INSERT INTO cs_FavoriteSections
				(OwnerID, SettingsID, SectionID, ApplicationType)
			VALUES
				(@UserID, @SettingsID, @ItemID, @ApplicationType)

			SET @FavoriteID = SCOPE_IDENTITY()
		END
	END

	ELSE IF @FavoriteType = 2	-- User
	BEGIN

		-- Check if favorite already exists, return existing id
		SELECT	@FavoriteID = F.FavoriteID
		FROM	cs_FavoriteUsers F
		WHERE	OwnerID = @UserID
			AND	SettingsID = @SettingsID
			AND	UserID = @ItemID
			AND	ApplicationType = @ApplicationType

		-- New favorite
		IF @FavoriteID IS NULL
		BEGIN

			INSERT INTO cs_FavoriteUsers
				(OwnerID, SettingsID, UserID, ApplicationType)
			VALUES
				(@UserID, @SettingsID, @ItemID, @ApplicationType)

			SET @FavoriteID = SCOPE_IDENTITY()
		END
	END

	ELSE IF @FavoriteType = 4	-- Post
	BEGIN

		-- Check if favorite already exists, return existing id
		SELECT	@FavoriteID = F.FavoriteID
		FROM	cs_FavoritePosts F
		WHERE	OwnerID = @UserID
			AND	SettingsID = @SettingsID
			AND	PostID = @ItemID
			AND	ApplicationType = @ApplicationType

		-- New favorite
		IF @FavoriteID IS NULL
		BEGIN

			INSERT INTO cs_FavoritePosts
				(OwnerID, SettingsID, PostID, ApplicationType)
			VALUES
				(@UserID, @SettingsID, @ItemID, @ApplicationType)

			SET @FavoriteID = SCOPE_IDENTITY()
		END
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorite_Add] to public
