module Jobs.Handler.HelpRequest
  ( dispatchJobHelpRequest
  ) where

import Import

import Text.Hamlet
import qualified Data.CaseInsensitive as CI

import Handler.Utils

import Utils.Lens

import Data.Bitraversable
  

dispatchJobHelpRequest :: Either (Maybe Address) UserId
                       -> UTCTime
                       -> Text -- ^ Help Request
                       -> Maybe Text -- ^ Referer
                       -> Handler ()
dispatchJobHelpRequest jSender jRequestTime jHelpRequest jReferer = do
  supportAddress <- getsYesod $ appMailSupport . appSettings
  userInfo <- bitraverse return (runDB . getEntity) jSender
  let userAddress = either
        id
        (fmap $ \(Entity _ User{..}) -> Address (Just userDisplayName) (CI.original userEmail))
        userInfo
  mailT def $ do
    _mailTo .= [supportAddress]
    whenIsJust userAddress $ addMailHeader "Reply-To" . renderAddress
    setSubjectI MsgMailSubjectSupport
    setDate jRequestTime
    rtime <- formatTimeMail SelFormatDateTime jRequestTime
    addPart ($(ihamletFile "templates/mail/support.hamlet") :: HtmlUrlI18n UniWorXMessage (Route UniWorX))
