﻿CREATE PROCEDURE [BO_GetKnokChartData]
	@KnokId BIGINT = NULL,
	@ShowEndedOnly BIT = NULL,
	@RangeSettings [DurationCRTAggrItemsList] readonly
AS
IF ISNULL(@ShowEndedOnly, 0) = 0
BEGIN
	SELECT T.* FROM (
	--Get rates for the active knoks
	SELECT k.KnokId as KnokId, CAST(CRT.Rate AS decimal(22, 8)) as Y, CRT.CRTD_Period as X 
	FROM [dbo].[VW_ActiveKnoks] k
	CROSS APPLY GetAppropriateCRTDataRange(k.Duration, k.Currency1, k.Currency2, k.ExchangeId, @RangeSettings) CRT
	WHERE 
		ISNULL(@KnokId, k.KnokId) = k.KnokId
		AND CRT.CRTD_Period >= k.CreateDate AND CRT.CRTD_Period <= DATEADD(day, k.Duration, k.CreateDate)

	UNION ALL

	--Get rate for the start date of the knok
	SELECT k.KnokId as KnokId,
	(SELECT TOP 1 CAST(MAX(CRT.Rate) AS decimal(22, 8)) as Y 
		FROM [dbo].[Signals] k1 
		CROSS APPLY GetAppropriateCRTDataRange(k1.Duration, k1.Currency1, k1.Currency2, k1.ExchangeId, @RangeSettings) CRT
		WHERE k.KnokId = k1.KnokId AND CRT.CRTD_Period <= k1.CreateDate
		GROUP BY k1.KnokId, k1.CreateDate, CRT.CRTD_Period
		ORDER BY CRT.CRTD_Period DESC), 
	k.CreateDate as X
	FROM [dbo].[Signals] k
	WHERE ISNULL(@KnokId, k.KnokId) = k.KnokId

	UNION ALL

	--Get rate for the current date
	SELECT k.KnokId as KnokId,
	(SELECT TOP 1 CAST(CRT.CRTD_BidClosingValue AS decimal(22, 8))
		FROM [Knoks_Prices].[dbo].[CRT_Data_LiveChart] CRT 
		WHERE CRT.CRTD_PairSymbol = k.Currency1 + k.Currency2 AND CRT.ExchangeId = k.ExchangeId
		AND CRT.CRTD_CreationDate <= GETUTCDATE() 
		--GROUP BY k.SignalId, k.CreateDate --, CRT.CRTD_Period
		ORDER BY CRT.CRTD_CreationDate DESC)  as Y, 
	GETUTCDATE() as X
	FROM [dbo].[Signals] k
	WHERE ISNULL(@KnokId, k.KnokId) = k.KnokId) T
	ORDER BY T.X
END
ELSE
BEGIN
	SELECT T.* FROM (
	--Get rates for the ended knoks
	SELECT k.KnokId as KnokId, CAST(CRT.Rate AS decimal(22, 8)) as Y, CRT.CRTD_Period as X 
	FROM [dbo].[VW_EndedKnoks] k
	CROSS APPLY GetAppropriateCRTDataRange(k.Duration, k.Currency1, k.Currency2, k.ExchangeId, @RangeSettings) CRT
	WHERE 
		ISNULL(@KnokId, k.KnokId) = k.KnokId
		AND CRT.CRTD_Period >= k.CreateDate AND CRT.CRTD_Period <= k.CloseDate
	
	UNION ALL

	SELECT k.KnokId as KnokId, CAST(k.CloseRate AS decimal(22, 8)) as Y, k.CloseDate as X 
	FROM [dbo].[VW_EndedKnoks] k
	WHERE 
		ISNULL(@KnokId, k.KnokId) = k.KnokId AND NOT k.CloseDate IS NULL) T
	ORDER BY T.X
END
RETURN 0
