-- SPDX-FileCopyrightText: 2022 Gregor Kleen <gregor.kleen@ifi.lmu.de>,Steffen Jost <jost@tcs.ifi.lmu.de>
--
-- SPDX-License-Identifier: AGPL-3.0-or-later

module Jobs.Handler.SendNotification
  ( dispatchJobSendNotification
  , dispatchJobUserNotification
  ) where

import Import

import Jobs.Types


import Jobs.Handler.SendNotification.SubmissionRated
import Jobs.Handler.SendNotification.SheetActive
import Jobs.Handler.SendNotification.SheetInactive
import Jobs.Handler.SendNotification.CorrectionsAssigned
import Jobs.Handler.SendNotification.CorrectionsNotDistributed
import Jobs.Handler.SendNotification.UserRightsUpdate
import Jobs.Handler.SendNotification.UserAuthModeUpdate
import Jobs.Handler.SendNotification.ExamActive
import Jobs.Handler.SendNotification.ExamResult
import Jobs.Handler.SendNotification.ExamOffice
import Jobs.Handler.SendNotification.CourseRegistered
import Jobs.Handler.SendNotification.SubmissionEdited
import Jobs.Handler.SendNotification.Qualification
import Jobs.Handler.QueueNotification (classifyNotification)

-- | send a notification directly, ignoring userNotificationSettings, assumed to be checked bt dispatchJobQueueNotification
dispatchJobSendNotification :: UserId -> Notification -> JobHandler UniWorX
dispatchJobSendNotification jRecipient jNotification = JobHandlerException $
  $(dispatchTH ''Notification) jNotification jRecipient

-- | like `dispatchJobSendNotification` but checks userNotificationSettings first
dispatchJobUserNotification :: UserId -> Notification -> JobHandler UniWorX
dispatchJobUserNotification jRecipient jNotification = JobHandlerException $ do
  ok <- runDB $ do 
    nTrigger <- classifyNotification jNotification
    get jRecipient <&> \case
      Just User{userNotificationSettings} 
        -> notificationAllowed userNotificationSettings nTrigger
      _ -> False
  when ok $
   $(dispatchTH ''Notification) jNotification jRecipient