{-# OPTIONS_GHC -fno-warn-unused-do-bind #-} -- ihamletFile discards do results

module Jobs.Handler.SendNotification.SubmissionRated
  ( dispatchNotificationSubmissionRated
  ) where

import Import

import Handler.Utils
import Jobs.Handler.SendNotification.Utils

import Text.Hamlet
import qualified Data.CaseInsensitive as CI


dispatchNotificationSubmissionRated :: SubmissionId -> UserId -> Handler ()
dispatchNotificationSubmissionRated nSubmission jRecipient = userMailT jRecipient $ do
  (Course{..}, Sheet{..}, Submission{..}, corrector, sheetTypeDesc) <- liftHandler . runDB $ do
    submission@Submission{submissionRatingBy} <- getJust nSubmission
    sheet <- belongsToJust submissionSheet submission
    course <- belongsToJust sheetCourse sheet
    corrector <- traverse getJust submissionRatingBy
    sheetTypeDesc <- sheetTypeDescription (sheetCourse sheet) (sheetType sheet)
    return (course, sheet, submission, corrector, sheetTypeDesc)

  whenIsJust corrector $ \corrector' ->
    addMailHeader "Reply-To" . renderAddress $ userAddressFrom corrector'
  replaceMailHeader "Auto-Submitted" $ Just "auto-generated"
  setSubjectI $ MsgMailSubjectSubmissionRated courseShorthand

  csid <- encrypt nSubmission
  MsgRenderer mr <- getMailMsgRenderer
  let termDesc = mr . ShortTermIdentifier $ unTermKey courseTerm
  submissionRatingTime' <- traverse (formatTimeMail SelFormatDateTime) submissionRatingTime
  let tid = courseTerm
      ssh = courseSchool
      csh = courseShorthand
      shn = sheetName

  editNotifications <- mkEditNotifications jRecipient

  addHtmlMarkdownAlternatives ($(ihamletFile "templates/mail/submissionRated.hamlet") :: HtmlUrlI18n (SomeMessage UniWorX) (Route UniWorX))
