module Handler.Course.News.Edit
  ( getCNEditR, postCNEditR
  ) where

import Import
import Handler.Utils

import Handler.Course.News.Form


getCNEditR, postCNEditR :: TermId -> SchoolId -> CourseShorthand -> CryptoUUIDCourseNews -> Handler Html
getCNEditR = postCNEditR
postCNEditR tid ssh csh cID = do
  nId <- decrypt cID
  (courseNews@CourseNews{..}, fids) <- runDB $ do
    courseNews <- get404 nId
    cnfs <- selectList [CourseNewsFileNews ==. nId] []
    return ( courseNews
           , cnfs ^.. folded . _entityVal . _FileReference . _1
           )

  ((newsRes, newsWgt'), newsEnctype) <- runFormPost . courseNewsForm . Just $ courseNewsToForm courseNews fids

  formResult newsRes $ \CourseNewsForm{..} -> do
    now <- liftIO getCurrentTime
    runDB $ do
      replace nId CourseNews
        { courseNewsCourse
        , courseNewsVisibleFrom      = cnfVisibleFrom
        , courseNewsParticipantsOnly = cnfParticipantsOnly
        , courseNewsTitle            = cnfTitle
        , courseNewsContent          = cnfContent
        , courseNewsSummary          = cnfSummary
        , courseNewsLastEdit         = now
        }
      let mkFilter CourseNewsFileResidual{} = [ CourseNewsFileNews ==. nId ]
       in void . replaceFileReferences mkFilter (CourseNewsFileResidual nId) $ sequence_ cnfFiles
    addMessageI Success MsgCourseNewsEdited
    redirect $ CourseR tid ssh csh CShowR :#: [st|news-#{toPathPiece cID}|]

  siteLayoutMsg MsgCourseNewsEdit $ do
    setTitleI MsgCourseNewsEdit

    wrapForm newsWgt' def
      { formAction = Just . SomeRoute $ CNewsR tid ssh csh cID CNEditR
      , formEncoding = newsEnctype
      }
