{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Worldcup.Rounds (Rounds, Round(..), parseRounds, lookupRound) where import Data.Aeson import Data.Aeson.Types as AET import Data.HashMap.Strict as HM import Data.Maybe as M import Prelude as P type Rounds = HashMap Int Round data Round = Round { roundId :: Int, roundEventId :: Int, roundName :: Value } deriving (Show) instance ToJSON Round where toJSON Round{..} = roundName instance FromJSON Round where parseJSON = withObject "round" $ \o -> do roundId <- o .: "id" roundEventId <- o .: "event_id" roundName <- o .: "title" return Round{..} parseRounds :: Either String [Value] -> Rounds parseRounds (Left x) = error x parseRounds (Right xs) = P.foldl reduce HM.empty xs where reduce acc x = case (parseEither parseJSON x :: Either String Round) of (Left s) -> error s (Right v) -> HM.insert (roundId v) v acc lookupRound :: Int -> Rounds -> Round lookupRound _id hm = M.fromMaybe (Round 999 999 "DNE") (HM.lookup _id hm)