module Handler.Course.Events.Edit
  ( getCEvEditR, postCEvEditR
  ) where

import Import
import Handler.Utils

import Handler.Course.Events.Form


getCEvEditR, postCEvEditR :: TermId -> SchoolId -> CourseShorthand -> CryptoUUIDCourseEvent -> Handler Html
getCEvEditR = postCEvEditR
postCEvEditR tid ssh csh cID = do
  eId <- decrypt cID
  courseEvent@CourseEvent{..} <- runDB $ get404 eId

  ((eventRes, eventWgt'), eventEnctype) <- runFormPost . courseEventForm . Just $ courseEventToForm courseEvent

  formResult eventRes $ \CourseEventForm{..} -> do
    now <- liftIO getCurrentTime
    runDB $
      replace eId CourseEvent
        { courseEventCourse
        , courseEventType = cefType
        , courseEventRoom = cefRoom
        , courseEventRoomHidden = cefRoomHidden
        , courseEventTime = cefTime
        , courseEventNote = cefNote
        , courseEventLastChanged = now
        }
    addMessageI Success MsgCourseEventEdited
    redirect $ CourseR tid ssh csh CShowR :#: [st|event-#{toPathPiece cID}|]

  siteLayoutMsg MsgMenuCourseEventEdit $ do
    setTitleI MsgMenuCourseEventEdit

    wrapForm eventWgt' def
      { formAction = Just . SomeRoute $ CEventR tid ssh csh cID CEvEditR
      , formEncoding = eventEnctype
      }

