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

import Import
import Handler.Utils

import Text.Blaze.Renderer.Text (renderMarkup)

import qualified Data.Conduit.List as C

import qualified Data.Set as Set


data CourseNewsForm = CourseNewsForm
  { cnfTitle            :: Maybe Text
  , cnfSummary          :: Maybe Html
  , cnfContent          :: Html
  , cnfParticipantsOnly :: Bool
  , cnfVisibleFrom      :: Maybe UTCTime
  , cnfFiles            :: Maybe (ConduitT () (Either FileId File) Handler ())
  }

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

  let oldFileIds = maybe (return mempty) (\s -> runConduit $ s .| C.foldMap (either opoint $ const mempty)) $ 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 & guardField (not . null . renderMarkup))
    (fslI MsgCourseNewsSummary & setTooltip MsgCourseNewsSummaryTip)
    (cnfSummary <$> template)
  cnfContent' <- wreq
    (htmlField & guardField (not . null . renderMarkup))
    (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 -> Set FileId -> CourseNewsForm
courseNewsToForm CourseNews{..} fs = CourseNewsForm
  { cnfTitle = courseNewsTitle
  , cnfSummary = courseNewsSummary
  , cnfContent = courseNewsContent
  , cnfParticipantsOnly = courseNewsParticipantsOnly
  , cnfVisibleFrom = courseNewsVisibleFrom
  , cnfFiles = guardOn (not $ Set.null fs) $ C.sourceList (Left <$> Set.toList fs)
  }
