module Jobs.Handler.SendCourseCommunication
  ( dispatchJobSendCourseCommunication
  ) where

import Import

import Text.Hamlet

import Handler.Utils

import qualified Data.CaseInsensitive as CI
import Handler.Utils.Csv (partIsAttachmentCsv)


{-# ANN module ("HLint: ignore Too strict maybe"::String) #-}


dispatchJobSendCourseCommunication :: Either UserEmail UserId
                                   -> Set Address
                                   -> CourseId
                                   -> UserId
                                   -> UUID
                                   -> Maybe Text
                                   -> Html
                                   -> JobHandler UniWorX
dispatchJobSendCourseCommunication jRecipientEmail jAllRecipientAddresses jCourse jSender jMailObjectUUID jSubject jMailContent = JobHandlerException $ do
  (sender, Course{..}) <- runDB $ (,)
    <$> getJust jSender
    <*> getJust jCourse
  either (\email -> mailT def . (assign _mailTo (pure . Address Nothing $ CI.original email) *>)) userMailT jRecipientEmail $ do
    MsgRenderer mr <- getMailMsgRenderer

    void $ setMailObjectUUID jMailObjectUUID
    _mailFrom .= userAddressFrom sender
    addMailHeader "Cc" [st|#{mr MsgCommUndisclosedRecipients}:;|]
    addMailHeader "Auto-Submitted" "no"
    setSubjectI . prependCourseTitle courseTerm courseSchool courseShorthand $ maybe (SomeMessage MsgCommCourseSubject) SomeMessage jSubject
    addHtmlMarkdownAlternatives ($(ihamletFile "templates/mail/courseCommunication.hamlet") :: HtmlUrlI18n UniWorXMessage (Route UniWorX))
    when (jRecipientEmail == Right jSender) $
      addPart' $ do
        partIsAttachmentCsv MsgCommAllRecipients
        toMailPart (MsgCommAllRecipientsSheet, toDefaultOrderedCsvRendered jAllRecipientAddresses)
