-- =============================================
-- Author:		<Dirk Strauss>
-- Create date:	<27 July 2017>
-- Description:	<Add or update an Uploaded document>
-- =============================================
CREATE PROCEDURE [dbo].[sproc_PROP1_FileUploader_AddUpdate] 
	@recId INT
	,@moduleId INT
	,@typeId INT
	,@folderName VARCHAR(350)
	,@entityId INT 
	,@display VARCHAR (350)
	,@fileName VARCHAR(350)
	,@dateSaved DATETIME
	,@dateUpdated DATETIME
	,@sequence INT
	,@isActive BIT
	,@userIdSaved INT
	,@userIdUpdated INT
	,@sourcePath VARCHAR(350)
	,@fieldName VARCHAR(500)
	,@isPrimary BIT
AS
BEGIN
	SET NOCOUNT ON;
	
     SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

	DECLARE @returnID INT = @recId
	DECLARE @insertAction INT = 0 -- false

	BEGIN TRANSACTION;	   
	-- Try update - The only update possible is the primary image flag
	   UPDATE [dbo].[pal_Attachment]
		 SET [moduleId] = @moduleId
		    ,[typeId] = @typeId
		    ,[folderName] = @folderName
		    ,[entityId] = @entityId
		    ,[display] = @display
		    ,[fileName] = @fileName
		    ,[dateSaved] = @dateSaved
		    ,[dateUpdated] = @dateUpdated
		    ,[sequence] = @sequence
		    ,[isActive] = @isActive
		    ,[userIdSaved] = @userIdSaved
		    ,[userIdUpdated] = @userIdUpdated
		    ,[sourcePath] = @sourcePath
		    ,[fieldName] = @fieldName
		    ,[isPrimary] = @isPrimary
	    WHERE [recId] = @recId AND isActive = 1;
	    
	IF @@ROWCOUNT = 0
	BEGIN

	   SET @insertAction = 1
	-- If nothing updated, try insert
	   INSERT INTO [dbo].[pal_Attachment]
			    ([moduleId]
			    ,[typeId]
			    ,[folderName]
			    ,[entityId]
			    ,[display]
			    ,[fileName]
			    ,[dateSaved]
			    ,[dateUpdated]
			    ,[sequence]
			    ,[isActive]
			    ,[userIdSaved]
			    ,[userIdUpdated]
			    ,[sourcePath]
			    ,[fieldName]
			    ,[isPrimary])
		   VALUES
			    (@moduleId
			    ,@typeId
			    ,@folderName
			    ,@entityId
			    ,@display
			    ,@fileName
			    ,@dateSaved
			    ,@dateUpdated
			    ,@sequence
			    ,@isActive
			    ,@userIdSaved
			    ,@userIdUpdated
			    ,@sourcePath
			    ,@fieldName
			    ,@isPrimary)

	END
		
	COMMIT TRANSACTION;
		
		IF (@insertAction =1)
		BEGIN
            SET @insertAction = @@IDENTITY
		END
          
		SELECT @insertAction
END
