module Utils.Sheet where

import Import.NoFoundation
import qualified Database.Esqueleto as E


-- DB Queries for Sheets that are used in several places

sheetCurrent :: MonadIO m => TermId -> SchoolId -> CourseShorthand -> SqlReadT m (Maybe SheetName)
sheetCurrent tid ssh csh = do
  now <- liftIO getCurrentTime
  sheets <- E.select . E.from $ \(course `E.InnerJoin` sheet) -> do
    E.on $ sheet      E.^. SheetCourse     E.==. course E.^. CourseId
    E.where_ $ sheet E.^. SheetActiveTo   E.>.  E.val now
        E.&&.  sheet E.^. SheetActiveFrom E.<=. E.val now
        E.&&. course E.^. CourseTerm      E.==. E.val tid
        E.&&. course E.^. CourseSchool    E.==. E.val ssh
        E.&&. course E.^. CourseShorthand E.==. E.val csh
    E.orderBy [E.asc $ sheet E.^. SheetActiveTo]
    E.limit 1
    return $ sheet E.^. SheetName
  return $ case sheets of
    [] -> Nothing
    [E.Value shn] -> Just shn
    _ -> error "SQL Query with limit 1 returned more than one result"


sheetOldUnassigned :: MonadIO m => TermId -> SchoolId -> CourseShorthand -> SqlReadT m (Maybe SheetName)
sheetOldUnassigned tid ssh csh = do
  now <- liftIO getCurrentTime
  sheets <- E.select . E.from $ \(course `E.InnerJoin` sheet) -> do
    E.on $ sheet     E.^. SheetCourse     E.==. course E.^. CourseId
    E.where_ $ sheet E.^. SheetActiveTo   E.<=. E.val now
        E.&&. course E.^. CourseTerm      E.==. E.val tid
        E.&&. course E.^. CourseSchool    E.==. E.val ssh
        E.&&. course E.^. CourseShorthand E.==. E.val csh
    E.where_ . E.exists . E.from $ \submission ->
        E.where_ $ submission E.^. SubmissionSheet E.==. sheet E.^. SheetId
          E.&&.  E.isNothing (submission E.^. SubmissionRatingBy)
    E.orderBy [E.asc $ sheet E.^. SheetActiveTo]
    E.limit 1
    return $ sheet E.^. SheetName
  return $ case sheets of
    [] -> Nothing
    [E.Value shn] -> Just shn
    _ -> error "SQL Query with limit 1 returned more than one result"
