{-# LANGUAGE OverloadedStrings #-}
module Millionaire where

import Control.Applicative
import Control.Monad
import Data.Aeson
import Data.ByteString.Lazy.UTF8 (fromString)
import Data.List (intercalate)
import Data.Maybe (fromMaybe)
import Data.Map (Map)
import qualified Data.Map as Map

data Question = Question { qText    :: String
                         , qAnswer  :: String
                         , qChoices :: Map String String
                         }

instance Show Question where
  show (Question question _ choices) =
    question ++ "\n\n" ++
    intercalate "\n" (map showChoice $ Map.toList choices) ++ "\n"
    where
      showChoice :: (String, String) -> String
      showChoice choice = fst choice ++ ") " ++ snd choice

instance FromJSON Question where
  parseJSON (Object v) = Question <$> v .: "question"
                                  <*> v .: "answer"
                                  <*> v .: "choices"
  parseJSON _          = mzero

isRight :: Question -> String -> Bool
isRight (Question _ rightAnswer _) userAnswer = userAnswer == rightAnswer

getRight :: Question -> String
getRight (Question _ rightAnswer _) = rightAnswer

getQuestions :: FilePath -> IO [Question]
getQuestions filepath = do
  questionsFile <- readFile filepath
  let questions = (decode . fromString) questionsFile :: Maybe [Question]
  return $ fromMaybe [] questions

askQuestion :: Question -> IO Bool
askQuestion question = do
  print question
  putStrLn "Answer: "
  answer <- getLine
  return $ isRight question answer
