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

module Jobs.Handler.SendNotification.UserRightsUpdate
  ( dispatchNotificationUserRightsUpdate
  , dispatchNotificationUserSystemFunctionsUpdate
  ) where

import Import

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

import qualified Data.Map as Map
import qualified Data.Set as Set

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

dispatchNotificationUserRightsUpdate :: UserId -> Set (SchoolFunction, SchoolShorthand) -> UserId -> Handler ()
dispatchNotificationUserRightsUpdate  nUser _originalRights jRecipient = userMailT jRecipient $ do
    (User{..}, functions)  <-  liftHandler . runDB $ do
      user <- getJust nUser
      functions <- Map.fromListWith Set.union . map (\(Entity _ UserFunction{..}) -> (userFunctionFunction, Set.singleton userFunctionSchool)) <$> selectList [UserFunctionUser ==. nUser] []
      return (user, functions)
    replaceMailHeader "Auto-Submitted" $ Just "auto-generated"
    setSubjectI $ MsgMailSubjectUserRightsUpdate userDisplayName
    -- MsgRenderer mr <- getMailMsgRenderer
    editNotifications <- mkEditNotifications jRecipient
    addHtmlMarkdownAlternatives ($(ihamletFile "templates/mail/userRightsUpdate.hamlet") :: HtmlUrlI18n (SomeMessage UniWorX) (Route UniWorX))


dispatchNotificationUserSystemFunctionsUpdate :: UserId -> Set SystemFunction -> UserId -> Handler ()
dispatchNotificationUserSystemFunctionsUpdate  nUser _originalSystemFunctions jRecipient = userMailT jRecipient $ do
    (User{..}, functions)  <-  liftHandler . runDB $ do
      user <- getJust nUser
      functions <- map (userSystemFunctionFunction . entityVal) <$> selectList [UserSystemFunctionUser ==. nUser] []
      return (user, Set.fromList functions)
    replaceMailHeader "Auto-Submitted" $ Just "auto-generated"
    setSubjectI $ MsgMailSubjectUserSystemFunctionsUpdate userDisplayName
    -- MsgRenderer mr <- getMailMsgRenderer
    editNotifications <- mkEditNotifications jRecipient
    addHtmlMarkdownAlternatives ($(ihamletFile "templates/mail/userSystemFunctionsUpdate.hamlet") :: HtmlUrlI18n (SomeMessage UniWorX) (Route UniWorX))

