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

import Import
import Handler.Utils

import Handler.Course.News.Form

import qualified Data.Set as Set

import qualified Data.Conduit.List as C


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
           , setOf (folded . _entityVal . _courseNewsFileFile) cnfs
           )

  ((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
        insertFile (Left  fId) = fId <$ upsertBy (UniqueCourseNewsFile nId fId) (CourseNewsFile nId fId) []
        insertFile (Right f  ) = insert f >>= \fId -> fId <$ insert_ (CourseNewsFile nId fId)
      newFids <- runConduit $ transPipe lift (fromMaybe (return ()) cnfFiles) .| C.mapM insertFile .| C.foldMap Set.singleton
      deleteWhere [ CourseNewsFileNews ==. nId, CourseNewsFileFile /<-. Set.toList newFids ]
    addMessageI Success MsgCourseNewsEdited
    redirect $ CourseR tid ssh csh CShowR :#: [st|news-#{toPathPiece cID}|]

  siteLayoutMsg MsgMenuCourseNewsEdit $ do
    setTitleI MsgMenuCourseNewsEdit

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