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

module Zero.GDAX.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.GDAX.API
import           Zero.GDAX.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 product prevDay evRefresh = do
  let (productTicker)
        = client gdaxAPI (Proxy :: Proxy m) (Proxy :: Proxy ()) baseUrl

  let userAgent = constDyn $ Right "Custom User Agent"
  evProductTicker <- productTicker userAgent product evRefresh

  let productTickerSuccess = fmapMaybe reqSuccess evProductTicker
      productTickerFailure = fmapMaybe reqFailure evProductTicker

  productTicker <- holdDyn defaultProductTicker productTickerSuccess

  let last = read . T.unpack <$> pt_price <$> productTicker

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