USE [DataPRO]
GO

/****** Object:  StoredProcedure [dbo].[sp_CompareGroupChannelSettings]    Script Date: 1/29/2019 11:34:29 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[sp_CompareGroupChannelSettings]

	@GroupId1			INT,
	@GroupId2			INT,
	@Result				BIT OUTPUT

AS
BEGIN
	BEGIN TRY
		DECLARE @tChannels1 table (
				 ChannelId				BIGINT
				,SensorId				INT
				,Processed				BIT)

		DECLARE @tChannels2 table (
				 ChannelId				BIGINT
				,SensorId				INT
				,Processed				BIT)
	
		INSERT INTO @tChannels1
		SELECT 	Id
			   ,SensorId
			   ,0
		FROM [dbo].[Channels] WHERE GroupId = @GroupId1 ORDER BY SensorId
	
		INSERT INTO @tChannels2
		SELECT 	Id
			   ,SensorId
			   ,0
		FROM [dbo].[Channels] WHERE GroupId = @GroupId2 ORDER BY SensorId
	
		IF ((SELECT COUNT(*) FROM @tChannels1) <> (SELECT COUNT(*) FROM @tChannels2))
		BEGIN
			SET @Result = 0
			RETURN;
		END
		ELSE
		BEGIN
			IF ((SELECT COUNT(*) FROM @tChannels1) > 0) -- Both counts should be the same
			BEGIN
				WHILE ((SELECT COUNT(*) From @tChannels1 Where Processed = 0) > 0)
				BEGIN
					DECLARE @ChannelId1			BIGINT
					DECLARE @ChannelId2			BIGINT
					DECLARE @TotalCountChannel1	INT
					DECLARE @TotalCountChannel2	INT
					DECLARE @IdenticalCount		INT

					SELECT TOP 1
								@ChannelId1		= ChannelId		
					FROM @tChannels1 WHERE Processed = 0 

					SELECT TOP 1
								@ChannelId2		= ChannelId		
					FROM @tChannels2 WHERE Processed = 0 

					SET @TotalCountChannel1 = dbo.foo_GetTotalGroupChannelSettingsCount(@ChannelId1)
					SET @TotalCountChannel2 = dbo.foo_GetTotalGroupChannelSettingsCount(@ChannelId2)
					IF (@TotalCountChannel1 <> @TotalCountChannel2)
					BEGIN
						SET @Result = 0
						RETURN
					END
					ELSE
					BEGIN
						IF (@TotalCountChannel1 > 0) -- Both total counts are the same
						BEGIN
							SET @IdenticalCount = [dbo].[foo_GetIdenticalGroupChannelSettingsCount](@ChannelId1, @ChannelId2)
							IF (@IdenticalCount <> @TotalCountChannel1) -- Both total counts are the same
							BEGIN
								SET @Result = 0
								RETURN
							END
						END

						UPDATE @tChannels1 set [Processed] = 1 where ChannelId = @ChannelId1
						UPDATE @tChannels2 set [Processed] = 1 where ChannelId = @ChannelId2
					END
				END
			END
			SET @Result = 1
		END
	END TRY
	BEGIN CATCH
		SET @Result = 0
	END CATCH
END


GO


