module Handler.Admin.Crontab
  ( getAdminCrontabR
  ) where

import Import
import Jobs
import Handler.Utils.DateTime

import Data.Aeson.Encode.Pretty (encodePrettyToTextBuilder)


getAdminCrontabR :: Handler Html
getAdminCrontabR = do
  jState <- getsYesod appJobState
  mCrontab' <- atomically . runMaybeT $ do
    JobState{jobCurrentCrontab} <- MaybeT $ tryReadTMVar jState
    MaybeT $ readTVar jobCurrentCrontab

  let mCrontab = mCrontab' <&> _2 %~ filter (hasn't $ _1 . _MatchNone)

  siteLayoutMsg MsgMenuAdminCrontab $ do
    setTitleI MsgMenuAdminCrontab
    [whamlet|
      $newline never
      $maybe (genTime, crontab) <- mCrontab
        <p>
          ^{formatTimeW SelFormatDateTime genTime}
        <table .table .table--striped .table--hover>
          $forall (match, job) <- crontab
            <tr .table__row>
              <td .table__td>
                $case match
                  $of MatchAsap
                    _{MsgCronMatchAsap}
                  $of MatchNone
                    _{MsgCronMatchNone}
                  $of MatchAt t
                    ^{formatTimeW SelFormatDateTime t}
              <td .table__td>
                <pre>
                  #{encodePrettyToTextBuilder job}
      $nothing
        _{MsgAdminCrontabNotGenerated}
    |]
