{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Worldcup.Teams (Teams, Team(..), parseTeams, lookupTeam) where import Data.Aeson import Data.Aeson.Types as AET import Data.HashMap.Strict as HM import Data.Maybe as M import Data.Scientific as S import Prelude as P type Teams = HashMap Int Team data Team = Team { teamId :: Int, teamCountryId :: Int } deriving (Show) instance ToJSON Team where toJSON Team{..} = Number $ scientific (P.toInteger teamCountryId) 0 instance FromJSON Team where parseJSON = withObject "team" $ \o -> do teamId <- o .: "id" teamCountryId <- o .: "country_id" return Team{..} parseTeams :: Either String [Value] -> Teams parseTeams (Left x) = error x parseTeams (Right xs) = P.foldl reduce HM.empty xs where reduce acc x = case (parseEither parseJSON x :: Either String Team) of (Left s) -> error s (Right v) -> HM.insert (teamId v) v acc lookupTeam :: Int -> Teams -> Team lookupTeam _id hm = M.fromMaybe (Team 999 999) (HM.lookup _id hm)