module Handler.Course.News.Form
  ( CourseNewsForm(..)
  , courseNewsForm
  , courseNewsToForm
  ) where

import Import
import Handler.Utils

import qualified Data.Conduit.List as C


data CourseNewsForm = CourseNewsForm
  { cnfTitle            :: Maybe Text
  , cnfSummary          :: Maybe StoredMarkup
  , cnfContent          :: StoredMarkup
  , cnfParticipantsOnly :: Bool
  , cnfVisibleFrom      :: Maybe UTCTime
  , cnfFiles            :: Maybe FileUploads
  }

courseNewsForm :: Maybe CourseNewsForm -> Form CourseNewsForm
courseNewsForm template = identifyForm FIDCourseNews . renderWForm FormStandard $ do
  now <- liftIO getCurrentTime

  let oldFileIds = fromMaybe (return ()) $ template >>= cnfFiles
      cTime = ceilingQuarterHour now
      visibleFromTip
        | Just vFrom <- template >>= cnfVisibleFrom
        , vFrom <= now
        = MsgCourseNewsVisibleFromEditWarning
        | otherwise
        = MsgCourseNewsVisibleFromTip

  cnfTitle' <- wopt
    (textField & cfStrip & guardField (not . null))
    (fslI MsgCourseNewsTitle)
    (cnfTitle <$> template)
  cnfSummary' <- wopt
    htmlField
    (fslI MsgCourseNewsSummary & setTooltip MsgCourseNewsSummaryTip)
    (cnfSummary <$> template)
  cnfContent' <- wreq
    htmlField
    (fslI MsgCourseNewsContent)
    (cnfContent <$> template)
  cnfParticipantsOnly' <- wpopt checkBoxField (fslI MsgCourseNewsParticipantsOnly) (cnfParticipantsOnly <$> template)
  cnfVisibleFrom' <- wopt utcTimeField (fslI MsgCourseNewsVisibleFrom & setTooltip visibleFromTip) (cnfVisibleFrom <$> template <|> Just (Just cTime))
  cnfFiles' <- wopt (multiFileField' oldFileIds) (fslI MsgCourseNewsFiles) (cnfFiles <$> template)

  return $ CourseNewsForm
    <$> cnfTitle'
    <*> cnfSummary'
    <*> cnfContent'
    <*> cnfParticipantsOnly'
    <*> cnfVisibleFrom'
    <*> cnfFiles'

courseNewsToForm :: CourseNews -> [FileReference] -> CourseNewsForm
courseNewsToForm CourseNews{..} fs = CourseNewsForm
  { cnfTitle = courseNewsTitle
  , cnfSummary = courseNewsSummary
  , cnfContent = courseNewsContent
  , cnfParticipantsOnly = courseNewsParticipantsOnly
  , cnfVisibleFrom = courseNewsVisibleFrom
  , cnfFiles = guardOn (not $ null fs) $ C.sourceList fs
  }
