module Handler.Course.News.Download
  ( getCNArchiveR
  , getCNFileR
  ) where

import Import
import Handler.Utils

import qualified Database.Esqueleto as E

import qualified Data.Conduit.List as C


getCNArchiveR :: TermId -> SchoolId -> CourseShorthand -> CryptoUUIDCourseNews -> Handler TypedContent
getCNArchiveR tid ssh csh cID = do
  nId <- decrypt cID
  CourseNews{..} <- runDB $ get404 nId

  archiveName <- fmap (flip addExtension (unpack extensionZip) . unpack). ap getMessageRender . pure $ MsgCourseNewsArchiveName tid ssh csh (fromMaybe (toPathPiece courseNewsLastEdit) courseNewsTitle)

  let getFilesQuery = (.| C.map entityVal) . E.selectSource . E.from $
        \newsFile -> do
          E.where_ $ newsFile E.^. CourseNewsFileNews E.==. E.val nId
          return newsFile

  serveSomeFiles archiveName getFilesQuery


getCNFileR :: TermId -> SchoolId -> CourseShorthand -> CryptoUUIDCourseNews -> FilePath -> Handler TypedContent
getCNFileR _ _ _ cID title = do
  nId <- decrypt cID

  let
    fileQuery = E.selectSource . E.from $ \newsFile -> do
        E.where_ $ newsFile E.^. CourseNewsFileNews  E.==. E.val nId
             E.&&. newsFile E.^. CourseNewsFileTitle E.==. E.val title
        return newsFile

  serveOneFile $ fileQuery .| C.map entityVal
