﻿ALTER PROCEDURE [dbo].[sp_TestSetupsDelete]
		 @TestSetupId		INT = 0,
		 @TestSetupName		NVARCHAR(50) = NULL,
		 @errorNumber		INT OUTPUT,
		 @errorMessage		NVARCHAR(255) OUTPUT
AS
BEGIN
	SET @errorNumber = 0; 	
	SET @errorMessage = SPACE(0);
	BEGIN TRY
	BEGIN TRANSACTION [tDeleteTestSetups]

		IF(@TestSetupId = 0)
		BEGIN
			SET @TestSetupId = [dbo].foo_IdGetTestSetup(@TestSetupName)
		END
					
		DELETE FROM [dbo].[TestSetupObjectMetaData]			where TestSetupId = @TestSetupId
		DELETE FROM [dbo].[TestSetupHardware]				where TestSetupId = @TestSetupId
		DELETE FROM [dbo].[LevelTriggers]					where TestSetupId = @TestSetupId
		DELETE FROM [dbo].[CalculatedChannels]				where TestSetupId = @TestSetupId
		DELETE FROM [dbo].[TestGraphs]						where TestSetupId = @TestSetupId

		/*Delete group channel settings*/		
		DELETE A FROM [dbo].[GroupChannelSettings] AS A INNER JOIN [dbo].[Channels] AS B ON A.ChannelId=B.Id 
			INNER JOIN [dbo].[Groups] AS C ON B.GroupId=C.Id INNER JOIN [dbo].TestSetupGroups AS D ON C.Id=D.GroupId WHERE D.TestSetupId=@TestSetupId
		/*Delete group hardware*/
		DELETE A FROM [dbo].[GroupHardware] AS A INNER JOIN [dbo].[TestSetupGroups] AS B ON A.GroupId=B.GroupId WHERE B.TestSetupId=@TestSetupId
		/*Delete group channels*/
		DELETE A FROM [dbo].[Channels] AS A INNER JOIN [dbo].[TestSetupGroups] AS B ON A.GroupId = B.GroupId WHERE B.TestSetupId=@TestSetupId
		/*grab a copy of all groups associated with test so we can delete them*/
		SELECT [GroupId] INTO #temptable FROM [dbo].[TestSetupGroups] WHERE [TestSetupId]=@TestSetupId
		/*unassociate the group from the test setup*/
		DELETE FROM [dbo].[TestSetupGroups] WHERE [TestSetupId] = @TestSetupId
		/*delete the groups*/
		DELETE FROM [dbo].[Groups] WHERE [Id] IN (SELECT [GroupId] FROM #tempTable)
		
		/*delete test specific hardware */
		UPDATE [dbo].[Channels] SET [DASId] = 0, [DASChannelIndex]=0 FROM [dbo].[Channels] AS A INNER JOIN [dbo].[DAS] AS B ON A.DASId=B.DASId WHERE B.TestId=@TestSetupId
		DELETE A FROM [dbo].[TestSetupHardware] AS A INNER JOIN [dbo].[DAS] as B ON A.DASId=B.DASId WHERE B.TestId=@TestSetupId
		DELETE A FROM [dbo].[GroupHardware] AS A INNER JOIN [dbo].[DAS] as B on A.DASId=B.DASId WHERE B.TestId=@TestSetupId
		DELETE A FROM [dbo].[DASChannels] AS A INNER JOIN [dbo].[DAS] AS B on A.DASId=B.DASId WHERE B.TestId=@TestSetupId
		DELETE [dbo].[DAS] WHERE [TestId]=@TestSetupId

		/*finally delete the test setup*/
		DELETE FROM [dbo].[TestSetups]					where TestSetupId = @TestSetupId		
		COMMIT TRANSACTION [tDeleteTestSetups]
	END TRY
	BEGIN CATCH
		SET @errorNumber = error_number()
		SET @errorMessage = error_message()
		ROLLBACK TRANSACTION [tDeleteTestSetups]
	END CATCH
END