CREATE PROCEDURE [dbo].[KST_UpdateKnok]
	@KnokId				BIGINT,
    @EntryPriceTouched	BIT = NULL, 
	@ExitPriceTouched	BIT = NULL, 
	@StopLossTouched	BIT = NULL, 
	@KnokStatusId		INT = NULL, 
	@HighRate			DECIMAL(22, 8) = NULL,
	@LowRate			DECIMAL(22, 8) = NULL,
	@KnokerWinRate		decimal(22, 8),
	@UserRefundRate		decimal(22, 8),
	@DistanceFromTarget decimal(22, 2) = NULL,
	@CloseRate			decimal(22, 8) = NULL
AS

DECLARE
		@TranStarted					bit,
		@RC								int,
		@ErrorMessage					nvarchar(1000),
		@TransId						bigint,
		
		@FollowersCount					int,
		@KnokPrice						decimal(22, 8),
		@KnokPublishPrice				decimal(22, 8),
		
		@UserId							bigint,
		@AccountId						bigint,
		@TransferAmount					decimal(22, 8),
		@PlatformUserId					bigint,
		@PlatformAccountId				bigint,
		@Comment						varchar(64)

BEGIN TRY 
	SET @RC = 0
	SET	@TranStarted = 0

	BEGIN TRANSACTION
	SET @TranStarted = 1
	IF ISNULL(@KnokStatusId, 0) = 5 --KNOK is resolved
	-- check for KnokerWinsToken
	BEGIN
		
		SELECT @KnokPrice = [Price],			
			@UserId = [CreatorUserId]
		FROM Signals WITH (NOLOCK) WHERE KnokId = @KnokId
		
		SELECT @KnokPublishPrice = [Amount], @AccountId = [AccountId]
		FROM [AccountTransactions] 
		WHERE 
			[AccountTransactionTypeId] = 4 --PublishKnok
			AND [KnokId] = @KnokId
			AND [UserId] = @UserId

		--user paid publish price so it is negative
		SET @KnokPublishPrice = - @KnokPublishPrice;

		SELECT @FollowersCount = COUNT([UserId]) FROM [UserKnoks] WHERE [KnokId] = @KnokId
		SET @TransferAmount = @FollowersCount * @KnokPrice * @KnokerWinRate + @KnokPublishPrice

		IF NOT @TransferAmount IS NULL 
		BEGIN
			SELECT @PlatformUserId = [UserId] FROM Users WHERE [UserTypeId] = 2 --Platform
			SET @PlatformAccountId = (SELECT TOP 1 [AccountId] FROM [Accounts] WHERE [UserId] = @PlatformUserId)

			SET @Comment = NEWID()

			--execute transaction
			EXEC	[dbo].[TRN_Account_TransferMoney]
			@FromUserId = @PlatformUserId,
			@FromAccountId = @PlatformAccountId,
			@FromExternalReferenceId = NULL,
			@FromWalletAddress = NULL,
		@FromAccountTransactionTypeId = 5, --KnokerWinsToken
			@ToUserId = @UserId,
			@ToAccountId = @AccountId,
			@ToExternalReferenceId = NULL,
			@ToWalletAddress = NULL,
		@ToAccountTransactionTypeId = 5, --KnokerWinsToken
			@Amount = @TransferAmount,
			@AmountUSD = NULL,
			@OperatorId = NULL,
			@Comment = @Comment,
			@PendingId = NULL,
			@KnokId = @KnokId
		END

		--Recalc DistanceFromTarget for User		
		SELECT @DistanceFromTarget = DistanceFromTarget FROM Signals WHERE KnokId = @KnokId AND ISNULL(@DistanceFromTarget, 0) = 0   
		IF ISNULL(@DistanceFromTarget, 0) <> 0 
		BEGIN
			UPDATE Users SET DistanceFromTarget =
				(SELECT ((SUM(ISNULL(DistanceFromTarget, 0))) + @DistanceFromTarget) / (COUNT(1) + 1)
				FROM Signals k
				WHERE KnokStatusId = 5 --Resolved 
					AND KnokId <> @KnokId AND CreatorUserId = UserId)
			WHERE UserId = @UserId;
		END

		--Recalc SuccessRate
		UPDATE Users SET SuccessRate =
			(SELECT
				ROUND((SELECT COUNT(1)
					FROM Signals sk
					WHERE sk.KnokStatusId = 5 --Resolved 
						AND sk.EntryPriceTouched = 1 AND sk.ExitPriceTouched = 1 AND sk.StopLossTouched = 0 AND sk.CreatorUserId = UserId) /				
				CAST(COUNT(1) AS DECIMAL(22,8)) * 100, 0)
				FROM Signals k
				WHERE k.CreatorUserId = UserId)
		WHERE UserId = @UserId

		--Recalc SuccessSequence
		if ISNULL(@EntryPriceTouched, 0) = 1 AND ISNULL(@ExitPriceTouched, 0) = 1 
		BEGIN
			UPDATE Users SET SuccessSequence = SuccessSequence+1 WHERE UserId = @UserId
		END

		if ISNULL(@StopLossTouched, 0) = 1 
		BEGIN
			UPDATE Users SET SuccessSequence = 0  WHERE UserId = @UserId
		END
	END --KNOK is resolved


	UPDATE Signals
	SET [EntryPriceTouched]		= ISNULL(@EntryPriceTouched, [EntryPriceTouched]),
		[ExitPriceTouched]		= ISNULL(@ExitPriceTouched, [ExitPriceTouched]),
		[StopLossTouched]		= ISNULL(@StopLossTouched, [StopLossTouched]),
		[KnokStatusId]			= ISNULL(@KnokStatusId, [KnokStatusId]),
		[HighRate]				= ISNULL(@HighRate, [HighRate]),
		[LowRate]				= ISNULL(@LowRate, [LowRate]),
		[CloseDate]				= IIF(ISNULL(@KnokStatusId, 0) = 5, GETUTCDATE(), [CloseDate]),
		[CloseRate]				= ISNULL(@CloseRate, [CloseRate]),
		[DistanceFromTarget]	= ISNULL(@DistanceFromTarget, [DistanceFromTarget]) 
	WHERE
		KnokId = @KnokId


	EXEC KST_GetKnoks @KnokId = @KnokId

	
	IF( @TranStarted = 1 )            
		COMMIT TRANSACTION            

	RETURN 0

END TRY           
BEGIN CATCH            
    IF( @TranStarted = 1 )            
		ROLLBACK TRANSACTION            

	EXEC [USP_LogError]           
	EXEC [USP_RethrowError]   
	
	IF @RC = 0 
		SET @RC = 1			         
	RETURN @RC
END CATCH