module Model.User
  ( getUsers
  , getUser
  , getJsonUser
  , createUser
  , deleteUser
  ) where

import Data.Text (Text)
import Data.Time.Clock (getCurrentTime)

import Control.Monad.IO.Class (liftIO)

import Database.Persist

import Model.Database
import qualified Model.Json.User as Json

getUsers :: Persist [Entity User]
getUsers = selectList [] [Desc UserCreation]

getUser :: Text -> Persist (Maybe (Entity User))
getUser email = selectFirst [UserEmail ==. email] []

getJsonUser :: Entity User -> Json.User
getJsonUser userEntity =
  let user = entityVal userEntity
  in  Json.User (entityKey userEntity) (userName user) (userEmail user)

createUser :: Text -> Text -> Persist UserId
createUser email name = do
  now <- liftIO getCurrentTime
  insert $ User now email name

deleteUser :: Text -> Persist ()
deleteUser email =
  deleteWhere [UserEmail ==. email]