module Handler.ExamOffice.ExternalExam
  ( getEEGradesR, postEEGradesR
  ) where

import Import

import Handler.Utils

import Handler.Utils.ExternalExam.Users

getEEGradesR, postEEGradesR :: TermId -> SchoolId -> CourseName -> ExamName -> Handler Html
getEEGradesR = postEEGradesR
postEEGradesR tid ssh coursen examn = do
  (usersResult, table) <- runDB $ do
    eExam <- getBy404 $ UniqueExternalExam tid ssh coursen examn
    (usersResult, examUsersTable) <- makeExternalExamUsersTable EEUMGrades eExam

    usersResult' <- formResultMaybe usersResult $ \case
      (ExternalExamUserMarkSynchronisedData, selectedResults) -> do
        forM_ selectedResults externalExamResultMarkSynchronised
        return . Just $ do
          addMessageI Success $ MsgExamUserMarkedSynchronised $ length selectedResults
          redirect $ EExamR tid ssh coursen examn EEGradesR
      _other -> return Nothing

    return (usersResult', examUsersTable)

  whenIsJust usersResult join

  hasUsers <- hasReadAccessTo $ EExamR tid ssh coursen examn EEUsersR

  siteLayoutMsg (MsgExternalExamGrades coursen examn) $ do
    setTitleI MsgBreadcrumbExternalExamGrades
    let examGradesExplanation = notificationWidget NotificationBroad Info $(i18nWidgetFile "exam-office/exam-grades-explanation")
    $(widgetFile "exam-office/externalExamGrades")
