﻿CREATE PROCEDURE [dbo].[sp_LockUpdate]     
     @UserId					INT				= NULL
     ,@UserName					NVARCHAR(50)	= NULL
     ,@ItemId					INT				= NULL
	 ,@CategoryId				INT
	 ,@MachineName				NVARCHAR(50)
     ,@errorNumber				INT				OUTPUT
     ,@errorMessage				NVARCHAR(250)	OUTPUT
	 ,@LockingUser			    NVARCHAR(50)	OUTPUT
	 ,@LockingMachine			NVARCHAR(50)	OUTPUT
	 ,@LastUsedTime             DATETIME		OUTPUT
	 ,@LockCreateTime			DATETIME		OUTPUT     
AS
BEGIN
 SET @errorNumber = 0 
 SET @errorMessage = space(0)
 SET @LockingUser = space(0)
 SET @LockingMachine = space(0)
 SET @LastUsedTime = null
 SET @LockCreateTime = null
 
 IF(@UserId) IS NULL
 BEGIN
  IF NOT EXISTS( SELECT ID FROM Users WHERE UserName=@UserName)
  BEGIN
   SET @errorNumber = 2
   SET @errorMessage = 'User not found'
   return -1
  END
 END

 IF NOT EXISTS( SELECT LockId FROM LockedItems WHERE CategoryId=@CategoryId AND ItemId=@ItemId AND DataPROUserID=@UserId AND MachineName=@MachineName)
 BEGIN
	IF EXISTS( SELECT LockId FROM LockedItems WHERE CategoryId=@CategoryId AND ItemId=@ItemId)
	BEGIN
		SET @errorNumber = 4
		SET @errorMessage = 'Locked by another user'
		SELECT @LockingUser = B.UserName, @LockingMachine=A.MachineName, @LastUsedTime=A.LastTouch, @LockCreateTime=A.StartTime FROM LockedItems as A INNER JOIN Users as B on A.DataPROUserID=B.ID WHERE A.CategoryId=@CategoryId AND A.ItemId=@ItemId
	END
	ELSE
		BEGIN
			SET @errorNumber = 3
			SET @errorMessage = 'No lock to update'
			return -1
		END
 END
 ELSE
 BEGIN   
  DECLARE @UpdateTime DateTime
  SET @UpdateTime = GetDate()
  UPDATE LockedItems Set LastTouch=@UpdateTime WHERE CategoryId=@CategoryId AND ItemId=@ItemId AND DataPROUserID=@UserId
 END
END