{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Worldcup.Continents (Continents, Continent(..), parseContinents, lookupContinent) where import Data.Aeson import Data.Aeson.Types as AET import Data.HashMap.Strict as HM import Data.Maybe as M import Data.Text as T import Prelude as P type Continents = HashMap Int Continent data Continent = Continent { continentId :: Int, continentName :: String } deriving (Show) instance ToJSON Continent where toJSON Continent{..} = String $ T.pack continentName parseContinents :: Either String [Value] -> Continents parseContinents (Left x) = error x parseContinents (Right xs) = P.foldl reduce HM.empty xs where reduce acc x = case (parseEither parseJSON x :: Either String Continent) of (Left s) -> error s (Right v) -> HM.insert (continentId v) v acc lookupContinent :: Int -> Continents -> Continent lookupContinent _id hm = M.fromMaybe (Continent 999 "DNE") (HM.lookup _id hm) instance FromJSON Continent where parseJSON = withObject "continent" $ \o -> do continentId <- o .: "id" continentName <- o .: "name" return Continent{..}