module Zero.Bittrex.Internal
  (
    Message(..)
  , MarketSummary(..)

  , defaultMessage
  , defaultMarketSummary
  ) where

import           GHC.Generics (Generic)
import           Data.Aeson
import           Data.Text (Text)

------------------------------------------------------------------------------
-- Generic Message
------------------------------------------------------------------------------

data Message a = Message {
    m_success :: Bool
  , m_message :: Text
  , m_result :: a
  } deriving (Show, Generic)

defaultMessage :: Message [MarketSummary]
defaultMessage =
  Message False "" [defaultMarketSummary]

instance FromJSON a => FromJSON (Message a) where
  parseJSON = withObject "Message" $ \v -> Message
    <$> v .: "success"
    <*> v .: "message"
    <*> v .: "result"

instance ToJSON a => ToJSON (Message a) where
  toJSON (Message success message result) =
    object [
      "success" .= success
    , "message" .= message
    , "result" .= result
    ]

------------------------------------------------------------------------------
-- Types
------------------------------------------------------------------------------

data MarketSummary = MarketSummary {
    ms_marketName :: Text
  , ms_high :: Double
  , ms_low :: Double
  , ms_volume :: Double
  , ms_last :: Double
  , ms_baseVolume :: Double
  , ms_timeStamp :: Text
  , ms_bid :: Double
  , ms_ask :: Double
  , ms_openBuyOrders :: Integer
  , ms_openSellOrders :: Integer
  , ms_prevDay :: Double
  , ms_created :: Text
  , ms_displayMarketName :: Maybe Text
  } deriving (Show, Generic)

defaultMarketSummary :: MarketSummary
defaultMarketSummary =
  MarketSummary "" 0.0 0.0 0.0 0.0 0.0 "" 0.0 0.0 0 0 0.0 "" Nothing

instance FromJSON MarketSummary where
  parseJSON = withObject "MarketSummary" $ \v -> MarketSummary
    <$> v .: "MarketName"
    <*> v .: "High"
    <*> v .: "Low"
    <*> v .: "Volume"
    <*> v .: "Last"
    <*> v .: "BaseVolume"
    <*> v .: "TimeStamp"
    <*> v .: "Bid"
    <*> v .: "Ask"
    <*> v .: "OpenBuyOrders"
    <*> v .: "OpenSellOrders"
    <*> v .: "PrevDay"
    <*> v .: "Created"
    <*> v .:? "DisplayMarketName"

instance ToJSON MarketSummary where
  toJSON (MarketSummary a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14) =
    object [
      "MarketName" .= a1
    , "High" .= a2
    , "Low" .= a3
    , "Volume" .= a4
    , "Last" .= a5
    , "BaseVolume" .= a6
    , "TimeStamp" .= a7
    , "Bid" .= a8
    , "Ask" .= a9
    , "OpenBuyOrders" .= a10
    , "OpenSellOrders" .= a11
    , "PrevDay" .= a12
    , "Created" .= a13
    , "DisplayMarketName" .= a14
    ]
