{-# LANGUAGE FlexibleContexts, ViewPatterns #-}
-- |Request for a single order book by market id.
module Cryptsy.API.Public.OrderBook
	( module Cryptsy.API.Public.OrderBook
	, module Cryptsy.API.Public.Types.Monad
	, module Cryptsy.API.Public.Types.OrderBook
	)
where

-- aeson
import Data.Aeson (FromJSON(..), withObject)

-- text
import Data.Text (Text, unpack)

-- unordered-containers
import Data.HashMap.Strict (toList)

-- this package
import Cryptsy.API.Public.Internal
import Cryptsy.API.Public.Types.Monad
import Cryptsy.API.Public.Types.OrderBook

-- |single orderbook API request
singleOrderBook :: FromJSON (GOrderBook p q t)
                => Text -- ^ marketid
                -> PubCryptsy (GOrderBook p q t)
singleOrderBook (unpack -> reqMarket) =
	pubCryptsy orderBookURL parseSingleOrderBook
 where
	orderBookURL = pubURL $ "singleorderdata&marketid=" ++ reqMarket
	parseSingleOrderBook = withObject dataStr $ \o ->
		case toList o of
			[]       -> fail "No order book returned."
			[(_, v)] -> parseJSON v
			_        -> fail "Multiple order books returned."
{-# INLINABLE singleOrderBook #-}