module Handler.Sheet.Delete
  ( getSDelR, postSDelR
  ) where

import Import

import Handler.Utils.Delete
import Handler.Utils.Sheet

import qualified Database.Esqueleto.Legacy as E

import qualified Data.Set as Set


sheetDeleteRoute :: Set SheetId -> DeleteRoute Sheet
sheetDeleteRoute drRecords = DeleteRoute
  { drRecords
  , drGetInfo = \(sheet `E.InnerJoin` course `E.InnerJoin` school) -> do
      E.on $ school E.^. SchoolId E.==. course E.^. CourseSchool
      E.on $ course E.^. CourseId E.==. sheet E.^. SheetCourse
      let submissions = E.subSelectCount . E.from $ \submission ->
            E.where_ $ submission E.^. SubmissionSheet E.==. sheet E.^. SheetId
      E.orderBy [E.asc $ sheet E.^. SheetName]
      return (submissions, sheet E.^. SheetName, course E.^. CourseShorthand, course E.^. CourseName, school E.^. SchoolShorthand, school E.^. SchoolName, course E.^. CourseTerm)
  , drUnjoin = \(sheet `E.InnerJoin` _ `E.InnerJoin` _) -> sheet
  , drRenderRecord = \(E.Value submissions, E.Value shn', _, E.Value cName, _, E.Value sName, E.Value tid') ->
      return [whamlet|
        $newline never
        #{shn'} (_{SomeMessage $ ShortTermIdentifier (unTermKey tid')}, #{sName}, #{cName})
        $if submissions /= 0
          &nbsp;<i>_{SomeMessage $ MsgSheetDelHasSubmissions submissions}
      |]
  , drRecordConfirmString = \(E.Value submissions, E.Value shn', E.Value csh', _, E.Value ssh', _, E.Value tid') ->
      return $ [st|#{termToText (unTermKey tid')}/#{ssh'}/#{csh'}/#{shn'}|] <> bool mempty [st| + #{tshow submissions} Subs|] (submissions /= 0)
  , drCaption = SomeMessage MsgSheetDeleteQuestion
  , drSuccessMessage = SomeMessage MsgSheetDeleted
  , drFormMessage = const $ return Nothing
  , drAbort = error "drAbort undefined"
  , drSuccess = error "drSuccess undefined"
  , drDelete = const id  -- TODO: audit
  }

getSDelR, postSDelR :: TermId -> SchoolId -> CourseShorthand -> SheetName -> Handler Html
getSDelR = postSDelR
postSDelR tid ssh csh shn = do
  sid <- runDB $ fetchSheetId tid ssh csh shn
  deleteR $ (sheetDeleteRoute $ Set.singleton sid)
    { drAbort = SomeRoute $ CSheetR tid ssh csh shn SShowR
    , drSuccess = SomeRoute $ CourseR tid ssh csh SheetListR
    }
