module Handler.Course.News.New
  ( getCNewsNewR, postCNewsNewR
  ) where

import Import
import Handler.Utils

import Handler.Course.News.Form

import qualified Data.Conduit.List as C


getCNewsNewR, postCNewsNewR :: TermId -> SchoolId -> CourseShorthand -> Handler Html
getCNewsNewR = postCNewsNewR
postCNewsNewR tid ssh csh = do
  cid <- runDB . getKeyBy404 $ TermSchoolCourseShort tid ssh csh

  ((newsRes, newsWgt'), newsEnctype) <- runFormPost $ courseNewsForm Nothing

  formResult newsRes $ \CourseNewsForm{..} -> do
    now <- liftIO getCurrentTime
    cID <- runDB $ do
      nId <- insert CourseNews
        { courseNewsCourse           = cid
        , courseNewsVisibleFrom      = cnfVisibleFrom
        , courseNewsParticipantsOnly = cnfParticipantsOnly
        , courseNewsTitle            = cnfTitle
        , courseNewsContent          = cnfContent
        , courseNewsSummary          = cnfSummary
        , courseNewsLastEdit         = now
        }
      let
        insertFile = insert_ . review _FileReference . (, CourseNewsFileResidual nId)
      forM_ cnfFiles $ \fSource ->
        runConduit $ transPipe lift fSource .| C.mapM_ insertFile
      encrypt nId :: DB CryptoUUIDCourseNews
    addMessageI Success MsgCourseNewsCreated
    redirect $ CourseR tid ssh csh CShowR :#: [st|news-#{toPathPiece cID}|]

  siteLayoutMsg MsgCourseNewsNew $ do
    setTitleI MsgCourseNewsNew

    wrapForm newsWgt' def
      { formAction = Just . SomeRoute $ CourseR tid ssh csh CNewsNewR
      , formEncoding = newsEnctype
      }
