﻿CREATE PROCEDURE [dbo].[BO_ExchangeCurrencies]
	@ExchangeId int = NULL,
	@AvailableKnoks BIT = null,
	@ActiveKnoks BIT = null,
	@EndedKnoks BIT = null,
	@UserId bigint = null
AS

if @AvailableKnoks = 1
	SELECT DISTINCT e.ExchangeId, e.ExchangeName, k.Currency1, k.Currency2
	from [Exchanges] e
		 inner join [VW_PublicKnoks] k on k.ExchangeId = e.ExchangeId
   	where e.IsActive = 1 AND e.ExchangeId = ISNULL(@ExchangeId, e.ExchangeId)
else if @ActiveKnoks = 1
	SELECT DISTINCT e.ExchangeId, e.ExchangeName, k.Currency1, k.Currency2
	from [Exchanges] e
		 inner join [VW_ActiveKnoks] k on k.ExchangeId = e.ExchangeId
   	where e.IsActive = 1 AND e.ExchangeId = ISNULL(@ExchangeId, e.ExchangeId)
		 AND (EXISTS (SELECT 1 FROM UserKnoks uk WHERE uk.UserId = @UserId AND uk.KnokId = k.KnokId))
else if @EndedKnoks = 1
	SELECT DISTINCT e.ExchangeId, e.ExchangeName, k.Currency1, k.Currency2
	from [Exchanges] e
		 inner join [VW_EndedKnoks] k on k.ExchangeId = e.ExchangeId
   	where e.IsActive = 1 AND e.ExchangeId = ISNULL(@ExchangeId, e.ExchangeId)
		 AND (EXISTS (SELECT 1 FROM UserKnoks uk WHERE uk.UserId = @UserId AND uk.KnokId = k.KnokId))
else
	SELECT DISTINCT e.ExchangeId, e.ExchangeName, t.Base as Currency1, t.NonBase as Currency2, t.Currency, t.TickerDisplayName from Tickers t 
		 left join [Exchanges] e  on t.ExchangeId = e.ExchangeId 
	where e.IsActive = 1 AND t.ExchangeId = ISNULL(@ExchangeId, t.ExchangeId)
RETURN 0