﻿CREATE PROCEDURE [BO_GetCurrentlyPublishedKnoks]
	@UserId BIGINT,
	@SortOrderAsc BIT = 0,
    @SortField INT = 1,
    @ExchangesIdsString NVARCHAR(1024) = NULL,
    @TradingPairsString NVARCHAR(1024) = NULL,
	@Gaining BIT = 0,
	@Losing BIT = 0,
	@KnokFeedExpirationHours INT = NULL,
	@RangeSettings [DurationCRTAggrItemsList] readonly
	AS     

	declare @ExchangesIds TABLE(id int NULL);
	declare @TradingPairs TABLE(code nvarchar(255) NULL);

	insert into @ExchangesIds(id) SELECT cast(value as int) 
		FROM STRING_SPLIT(@ExchangesIdsString, ';')

	insert into @TradingPairs(code) SELECT value 
		FROM STRING_SPLIT(@TradingPairsString, ';')

	--Get active knoks
	SELECT Duration, CreateDate, KnokId, Currency1, Currency2, Currency, MarketDisplayName, ExchangeId, UserId, 
		EntryPriceFrom, EntryPriceTo, ExitPriceFrom,  ExitPriceTo, StopLoss, ExchangeName,
		PotentialProfitValue, PotentialProfit, Price, DollarPrice, UserFollowers, [Rank],
	    HasAvatar, UserName, FirstName, LastName, CurrentPrice, Purchases, CurrentProfit, --DistanceFromTarget,
		k.PricePoolData,
		k.UserReview,
		k.Precision,
		(CASE WHEN NOT @KnokFeedExpirationHours IS NULL AND DATEDIFF(MINUTE, GETUTCDATE(), DATEADD(HOUR, @KnokFeedExpirationHours, k.CreateDate)) >  0 
			THEN DATEDIFF(MINUTE, GETUTCDATE(), DATEADD(HOUR, @KnokFeedExpirationHours, k.CreateDate)) ELSE 0 END) AS MinutesLeftOnFeed
	
	FROM [dbo].[VW_ActiveKnoks] k with(nolock) 
	Where k.UserId = @UserId
		AND (EXISTS(SELECT 1 FROM @ExchangesIds HAVING COUNT(1) = 0) OR EXISTS (SELECT 1 FROM @ExchangesIds e WHERE e.id = k.ExchangeId))
		AND (EXISTS(SELECT 1 FROM @TradingPairs HAVING COUNT(1) = 0) OR EXISTS (SELECT 1 FROM @TradingPairs e WHERE e.code = k.Currency2))
		AND ((@Gaining = 1 AND @Losing = 1) OR 
			(ISNULL(@Gaining, 0) = 0 OR (@Gaining = 1 AND CurrentPrice > ((EntryPriceFrom + EntryPriceTo) / 2)))
				AND (ISNULL(@Losing, 0) = 0 OR (@Losing = 1 AND CurrentPrice < ((EntryPriceFrom + EntryPriceTo) / 2)))
		)
	ORDER BY
		CASE @SortOrderAsc WHEN 1 THEN
				CASE @SortField 
					WHEN 1 THEN TimeLeft -- TimeLeft
					WHEN 2 THEN DistanceFromTarget -- Distance from target
					--WHEN 3 THEN CurrentProfit -- Current profit
					--WHEN 4 THEN Purchases -- Purchases
					WHEN 5 THEN PricePoolData -- PricePool
					WHEN 6 THEN UserReview -- BuyerReview
				END
		END ASC,

		CASE @SortOrderAsc WHEN 0 THEN
				CASE @SortField 
					WHEN 1 THEN TimeLeft -- TimeLeft
					WHEN 2 THEN DistanceFromTarget -- Distance from target
					--WHEN 3 THEN CurrentProfit -- Current profit
					--WHEN 4 THEN Purchases -- Purchases
					WHEN 5 THEN PricePoolData -- PricePool
					WHEN 6 THEN UserReview -- BuyerReview
				END
		END DESC

	EXEC [BO_GetKnokChartData] NULL, NULL, @RangeSettings

RETURN 0 