{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Worldcup.Countries (Countries, Country(..), parseCountries, lookupCountry) 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 Countries = HashMap Int Country data Country = Country { countryId :: Int, countryContinentId :: Int, countryName :: String } deriving (Show) instance FromJSON Country where parseJSON = withObject "country" $ \o -> do countryId <- o .: "id" countryContinentId <- o .: "continent_id" countryName <- o .: "name" return Country{..} lookupCountry :: Int -> Countries -> Country lookupCountry _id hm = M.fromMaybe (Country 999 999 "DNE") (HM.lookup _id hm) parseCountries :: Either String [Value] -> Countries parseCountries (Left x) = error x parseCountries (Right xs) = P.foldl reduce HM.empty xs where reduce acc x = case (parseEither parseJSON x :: Either String Country) of (Left s) -> error s (Right v) -> HM.insert (countryId v) v acc