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

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

import Import

import Utils.Lens
import Handler.Utils.DateTime
import Handler.Utils.Mail
import Jobs.Handler.SendNotification.Utils

import Text.Hamlet
import qualified Data.Aeson as Aeson
import qualified Data.CaseInsensitive as CI

dispatchNotificationSubmissionRated :: SubmissionId -> UserId -> Handler ()
dispatchNotificationSubmissionRated nSubmission jRecipient = userMailT jRecipient $ do
  (Course{..}, Sheet{..}, Submission{..}, corrector) <- liftHandlerT . runDB $ do
    submission@Submission{submissionRatingBy} <- getJust nSubmission
    sheet <- belongsToJust submissionSheet submission
    course <- belongsToJust sheetCourse sheet
    corrector <- traverse getJust submissionRatingBy
    return (course, sheet, submission, corrector)
  replaceMailHeader "Auto-Submitted" $ Just "auto-generated"
  setSubjectI $ MsgMailSubjectSubmissionRated courseShorthand

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

  editNotifications <- mkEditNotifications jRecipient

  -- TODO: provide convienience template-haskell for `addAlternatives`
  addAlternatives $ do
    provideAlternative $ Aeson.object
      [ "submission" Aeson..= ciphertext csid
      , "submission-rating-points" Aeson..= (guard (sheetType /= NotGraded) *> submissionRatingPoints)
      , "submission-rating-comment" Aeson..= submissionRatingComment
      , "submission-rating-time" Aeson..= submissionRatingTime
      , "submission-rating-by" Aeson..= (userDisplayName <$> corrector)
      , "submission-rating-passed" Aeson..= join (gradingPassed <$> sheetType ^? _grading <*> submissionRatingPoints)      
      , "sheet-name" Aeson..= sheetName
      , "sheet-type" Aeson..= sheetType
      , "course-name" Aeson..= courseName
      , "course-shorthand" Aeson..= courseShorthand
      , "course-term" Aeson..= courseTerm
      , "course-school" Aeson..= courseSchool
      ]
    -- provideAlternative $ \(MsgRenderer mr) -> ($(textFile "templates/mail/submissionRated.txt") :: TextUrl (Route UniWorX)) -- textFile does not support control statements
    providePreferredAlternative ($(ihamletFile "templates/mail/submissionRated.hamlet") :: HtmlUrlI18n UniWorXMessage (Route UniWorX))
