{-# LANGUAGE RankNTypes       #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecursiveDo         #-}

module Zero.Bitstamp.Widget
  (
    TickerWidget(..)
  , tickerWidget
  ) where

import           Data.Proxy (Proxy(..))
import qualified Data.Text as T
import           Data.Text (Text)
import           Reflex.Dom.Core
import           Servant.API
import           Servant.Reflex
import           Zero.Bitstamp.API
import           Zero.Bitstamp.Internal
import           Zero.Settings.Client
import           Zero.Widget (diff24hDyn)

------------------------------------------------------------------------------
data TickerWidget t = TickerWidget {
    tw_marketName :: Dynamic t Text
  , tw_last :: Dynamic t Double
  , tw_24hDiff :: Dynamic t Double
  }

tickerWidget :: forall t m. (
    SupportsServantReflex t m
  , MonadWidget t m
  ) => Dynamic t (Either Text Text) -> Dynamic t Double -> Event t () -> m (TickerWidget t)
tickerWidget currencyPair prevDay evRefresh = do
  let (ticker)
        = client bitstampAPI (Proxy :: Proxy m) (Proxy :: Proxy ()) baseUrl

  let currencyPair = Right <$> constDyn "btcusd"
  evBitstampTicker <- ticker currencyPair evRefresh

  let bitstampTickerSuccess = fmapMaybe reqSuccess evBitstampTicker
      bitstampTickerFailure = fmapMaybe reqFailure evBitstampTicker

  ticker <- holdDyn defaultTicker bitstampTickerSuccess

  let last = read . T.unpack <$> t_last <$> ticker

  return TickerWidget {
      tw_marketName = constDyn "btcusd"
    , tw_last = last
    , tw_24hDiff = diff24hDyn prevDay last
    }
