CREATE PROCEDURE [MIG_SET_USERS_PREFERENCES_Sp]
(
	 @InputApp NVARCHAR(MAX),
	 @InputUser NVARCHAR(MAX)
)
AS BEGIN
	-- The purpose of this stored procedure is to generate/populate the data in [MIG_SW_PROPS] table.

	DECLARE @Itr_TargetPropName NVARCHAR(MAX)
	DECLARE @Itr_TargetControlType NVARCHAR(MAX)
	DECLARE @Itr_PropDescription NVARCHAR(MAX)
	DECLARE @Itr_LegacyPropName NVARCHAR(MAX)
	DECLARE @Itr_LegacyPropGuiType NVARCHAR(MAX)
	DECLARE @Itr_PropValue NVARCHAR(MAX)

	DECLARE @Data NVARCHAR(MAX)
	
	--Define cursor
	DECLARE RecordsCursor CURSOR  
	LOCAL FORWARD_ONLY FOR  
	SELECT 
		--SYS_PROPS.APP_NAME, 
		MIG_PROP_NAMES_MAPPING.PropName AS "TargetPropName",
		MIG_PROP_NAMES_MAPPING.ControlType AS "TargetControlType",
		MIG_PROP_NAMES_MAPPING.PropDescription AS "TargetPropDescription",
		-- PLM PREF in pd also have prefs of SYS CONFIG which are not available in SYS_PROPS
		-- So if Sys_PROP legacy is null go for MIG_PROP_NAME Legacy Prop Name
		IsNull(SYS_PROPS.PROP_NAME, MIG_PROP_NAMES_MAPPING.LegacyPropName) AS "LegacyPropName",   
		SYS_PROPS.PROP_GUI_TYPE AS "LegacyPropGuiType",
		CASE 
			WHEN USER_PROPS.PROP_VALUE IS NOT NULL THEN
				USER_PROPS.PROP_VALUE
			ELSE
				SYS_PROPS.PROP_VALUE
		END as 'PROP_VALUE'
	FROM MIG_PROP_NAMES_MAPPING
	LEFT JOIN SYS_PROPS
	  ON MIG_PROP_NAMES_MAPPING.AppName = SYS_PROPS.APP_NAME
	 AND MIG_PROP_NAMES_MAPPING.LegacyPropName = SYS_PROPS.PROP_NAME
	LEFT JOIN USER_PROPS
	  ON USER_PROPS.APP_NAME = SYS_PROPS.APP_NAME
	 AND USER_PROPS.PROP_NAME = SYS_PROPS.PROP_NAME
	 AND USER_PROPS.USER_ID = @InputUser
	WHERE MIG_PROP_NAMES_MAPPING.AppName = @InputApp 
	--AND LegacyPropName = 'CHECK_IN_CLEANUP'

	--Open cursor & iterate
	OPEN RecordsCursor  
	WHILE 1 = 1   
	BEGIN
		FETCH NEXT FROM RecordsCursor INTO  @Itr_TargetPropName, 
											@Itr_TargetControlType, 
											@Itr_PropDescription, 
											@Itr_LegacyPropName, 
											@Itr_LegacyPropGuiType,
											@Itr_PropValue
		IF @@FETCH_STATUS <> 0
			BREAK

		--Update specific preference.
		exec MIG_SET_USER_PREFERENCE_Sp		@InputUser, 
											@InputApp, 
											@Itr_TargetPropName, 
											@Itr_TargetControlType, 
											@Itr_PropDescription, 
											@Itr_LegacyPropName, 
											@Itr_LegacyPropGuiType,
											@Itr_PropValue
	END

	CLOSE RecordsCursor
END



