-- =============================================
-- Author:		DD MS
-- Changed: 
-- =============================================
CREATE PROCEDURE PRIDB_NEW_DYNAMIC_FOLDER_FOR_OBJECT @pIDB_OBJ_ID BIGINT, @pDYNAMIC_FOLDER VARCHAR(900),@pWHO VARCHAR(100),@pLANG_CODE VARCHAR(5)
AS
DECLARE
	@FOLD_PART	VARCHAR(250)
BEGIN								

	DECLARE @FOLDER_DEPTH TINYINT,@FOLDER_PART VARCHAR(900)
	SET @FOLDER_DEPTH = 0
	DECLARE @PARENT_OBJ_ID BIGINT
	--SPLIT FOR FOLDER PARTS
	DECLARE cursSplitFolder CURSOR FOR 
		SELECT Item FROM [dbo].[FN_SPLIT_STRING] (@pDYNAMIC_FOLDER,'\')
	OPEN cursSplitFolder 
		FETCH NEXT FROM cursSplitFolder INTO @FOLD_PART
		WHILE @@FETCH_STATUS = 0
		BEGIN
			--EACH FOLDER PART WORKED SEPERATELY
			IF @FOLDER_DEPTH = 0
				BEGIN
					SET @PARENT_OBJ_ID = 0
					SET @FOLDER_PART = @FOLD_PART
				END
			ELSE
				BEGIN
					SET @FOLDER_PART += '\' + @FOLD_PART
				END
			PRINT '##############################'
			PRINT '@FOLDER_PART: ' + @FOLDER_PART
			DECLARE @PATH_PART_ID BIGINT,@FOLDER_PART_ID BIGINT
			EXEC PRIDB_NEW_TERM 'VARCHAR',@FOLD_PART,@pWHO,@TERM_ID = @PATH_PART_ID OUTPUT;
			--EXEC PRIDB_NEW_TERM 'VARCHAR',@FOLDER_PART,'DD MS',@TERM_ID = @FOLDER_PART_ID OUTPUT;
			DECLARE @FOLD_PART_IDB_OBJ_ID BIGINT
				IF NOT EXISTS(SELECT * FROM VWIDB_STRUCTURE_NODES WHERE TERM_GUID = @PATH_PART_ID AND PARENT_OBJ_ID = @PARENT_OBJ_ID)
					BEGIN
						PRINT 'FOLDER-PART ' + @FOLD_PART +  ' muss angelegt werden'
						EXEC PRIDB_NEW_OBJECT 'DYNAMIC_FOLDER',@pWHO,0, @PARENT_OBJ_ID, @IDB_OBJ_ID = @FOLD_PART_IDB_OBJ_ID OUTPUT;
						DECLARE @NEW_OBJ_MD_ID BIGINT
						EXEC PRIDB_NEW_OBJ_DATA @FOLD_PART_IDB_OBJ_ID, 'VIRTUAL_FOLDER_PART', @pWHO, @FOLD_PART, @pLANG_CODE, 0, @OMD_ID = @NEW_OBJ_MD_ID OUTPUT
					END
				ELSE
					BEGIN
						SELECT @FOLD_PART_IDB_OBJ_ID = MAX(IDB_OBJ_ID) FROM VWIDB_STRUCTURE_NODES WHERE TERM_GUID = @PATH_PART_ID AND PARENT_OBJ_ID = @PARENT_OBJ_ID
						PRINT 'FOLDER-PART ' + @FOLD_PART +  ' EXISTIERT BEREITS'
					END
				SET @PARENT_OBJ_ID = @FOLD_PART_IDB_OBJ_ID

			SET @FOLDER_DEPTH += 1
			FETCH NEXT FROM cursSplitFolder INTO @FOLD_PART
		END
	CLOSE cursSplitFolder
	DEALLOCATE cursSplitFolder

	IF NOT EXISTS(SELECT GUID FROM TBIDB_OBJECT_DYNAMIC_FOLDER WHERE IDB_OBJ_ID = @pIDB_OBJ_ID AND DYN_FOLD_ID = @FOLD_PART_IDB_OBJ_ID)
			INSERT INTO TBIDB_OBJECT_DYNAMIC_FOLDER (IDB_OBJ_ID,DYN_FOLD_ID,ADDED_WHO) VALUES (@pIDB_OBJ_ID,@FOLD_PART_IDB_OBJ_ID,@pWHO);
END
