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

module Jobs.Handler.SendNotification.SheetInactive
  ( dispatchNotificationSheetSoonInactive
  , dispatchNotificationSheetInactive
  ) where

import Import

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

import Text.Hamlet
import qualified Data.CaseInsensitive as CI

import qualified Database.Esqueleto.Legacy as E

dispatchNotificationSheetSoonInactive :: SheetId -> UserId -> Handler ()
dispatchNotificationSheetSoonInactive nSheet jRecipient = userMailT jRecipient $ do
  (Course{..}, Sheet{..}) <- liftHandler . runDB $ do
    sheet <- getJust nSheet
    course <- belongsToJust sheetCourse sheet
    return (course, sheet)
  replaceMailHeader "Auto-Submitted" $ Just "auto-generated"
  setSubjectI $ MsgMailSubjectSheetSoonInactive courseShorthand sheetName

  MsgRenderer mr <- getMailMsgRenderer
  let termDesc = mr . ShortTermIdentifier $ unTermKey courseTerm
      tid = courseTerm
      ssh = courseSchool
      csh = courseShorthand
      shn = sheetName

  editNotifications <- mkEditNotifications jRecipient

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

dispatchNotificationSheetInactive :: SheetId -> UserId -> Handler ()
dispatchNotificationSheetInactive nSheet jRecipient = userMailT jRecipient $ do
  (Course{..}, Sheet{..}, nrSubs, nrSubmitters, nrPseudonyms, nrParticipants) <- liftHandler . runDB $ do
    sheet <- getJust nSheet
    course <- belongsToJust sheetCourse sheet
    nrSubs <- count [SubmissionSheet ==. nSheet]
    nrSubmitters <- fmap (maybe 0 (max 0 . E.unValue) . listToMaybe) . E.select . E.from $ \(subUser `E.InnerJoin` submission) -> do
        E.on $ subUser E.^. SubmissionUserSubmission E.==. submission E.^. SubmissionId
        E.where_ $ submission E.^. SubmissionSheet E.==. E.val nSheet
        -- E.distinctOn [E.don (subUser E.^. SubmissionUserUser)] -- Not necessary due to UniqueSubmisionUser
        return (E.countRows :: E.SqlExpr (E.Value Int64))
    nrPseudonyms <- count [SheetPseudonymSheet ==. nSheet]
    nrParticipants <- count [CourseParticipantCourse ==. sheetCourse sheet, CourseParticipantState ==. CourseParticipantActive]
    return (course, sheet, nrSubs, nrSubmitters, nrPseudonyms, nrParticipants)
  replaceMailHeader "Auto-Submitted" $ Just "auto-generated"
  setSubjectI $ MsgMailSubjectSheetInactive courseShorthand sheetName

  MsgRenderer mr <- getMailMsgRenderer
  let termDesc = mr . ShortTermIdentifier $ unTermKey courseTerm
      tid = courseTerm
      ssh = courseSchool
      csh = courseShorthand
      shn = sheetName

  editNotifications <- mkEditNotifications jRecipient

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

