ALTER PROCEDURE [sp_TestSetupLockUpdate]     
     @UserId					  int = null
     ,@UserName					  nvarchar(50) = null
     ,@TestSetupId				  int = null
     ,@TestSetupName			  nvarchar(50) = null
	 ,@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
 DECLARE @CategoryId INT
 
 IF NOT EXISTS( SELECT CategoryId FROM LockedItemCategories WHERE CategoryText='TestSetups')
 BEGIN
  INSERT INTO LockedItemCategories (CategoryText) VALUES ('TestSetups')
  SET @CategoryId = SCOPE_IDENTITY()
  SET @errorNumber = 3
  SET @errorMessage = 'No lock to update'
  return -1
 END
 ELSE
 BEGIN
  SELECT @CategoryId = CategoryId from LockedItemCategories WHERE CategoryText='TestSetups'
 END
 
 IF (@TestSetupId) IS NULL
 BEGIN
  IF NOT EXISTS( SELECT TestSetupId from TestSetups WHERE TestSetupName=@TestSetupName)
  BEGIN
   SET @errorNumber = 1
   SET @errorMessage = 'TestSetup not found'
   return -1
  END
  ELSE
  BEGIN
   SELECT @TestSetupId = TestSetupId from TestSetups where TestSetupName=@TestSetupName
  END
 END
 
 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=@TestSetupId AND DataPROUserID=@UserId AND MachineName=@MachineName)
 BEGIN
	IF EXISTS( SELECT LockId FROM LockedItems WHERE CategoryId=@CategoryId AND ItemId=@TestSetupId)
	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=@TestSetupId
	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=@TestSetupId AND DataPROUserID=@UserId
 END
END