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

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

import Import
import Handler.Utils

import qualified Database.Esqueleto.Legacy as E

import qualified Data.Conduit.List as C


cnArchiveSource :: CourseNewsId -> ConduitT () CourseNewsFile (YesodDB UniWorX) () 
cnArchiveSource nId = (.| C.map entityVal) . E.selectSource . E.from $ \newsFile -> do
  E.where_ $ newsFile E.^. CourseNewsFileNews E.==. E.val nId
  return newsFile
  
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)

  serveSomeFiles archiveName $ cnArchiveSource nId


cnFileSource :: CourseNewsId -> FilePath -> ConduitT () CourseNewsFile (YesodDB UniWorX) () 
cnFileSource nId fPath = (.| C.map entityVal) . E.selectSource . E.from $ \newsFile -> do
  E.where_ $ newsFile E.^. CourseNewsFileNews  E.==. E.val nId
       E.&&. newsFile E.^. CourseNewsFileTitle E.==. E.val fPath
  return newsFile
  
getCNFileR :: TermId -> SchoolId -> CourseShorthand -> CryptoUUIDCourseNews -> FilePath -> Handler TypedContent
getCNFileR _ _ _ cID fPath = do
  nId <- decrypt cID
  serveOneFile $ cnFileSource nId fPath
