module Job
  ( jobListener
  ) where

import Data.Time.Clock

import Control.Concurrent (threadDelay)

import Model.Database
import Model.JobKind
import Model.Job

jobListener :: JobKind -> (UTCTime -> IO Bool) -> (() -> Persist ()) -> Int -> IO ()
jobListener kind lastExecutionTooOld runJob msDelay = do
  mbLastExecution <- runDb $ do
    actualizeLastCheck kind
    getLastExecution kind
  hasToRun <- case mbLastExecution of
    Just lastExecution -> lastExecutionTooOld lastExecution
    Nothing -> return True
  if hasToRun
    then runDb (runJob () >> actualizeLastExecution kind)
    else return ()
  threadDelay msDelay
  jobListener kind lastExecutionTooOld runJob msDelay