module System.Touched.OnlyOne where
import System.Touched.Procedure
import Data.Maybe (maybe)
import Data.Time.Clock (UTCTime, getCurrentTime)
data OnlyOne a b = Inactive (Procedure a b)
| Active (Procedure a b) b UTCTime
otTime :: OnlyOne a b -> Maybe UTCTime
otTime (Active _ _ t0) = Just t0
otTime _ = Nothing
old :: OnlyOne a b -> UTCTime -> Bool
old ot utc = maybe True (<utc) $ otTime ot
otKill :: OnlyOne a b -> IO (OnlyOne a b)
otKill (Active p id _) = kill p id >>
return (Inactive p)
otKill ot = return ot
otStart :: OnlyOne a b -> IO (OnlyOne a b)
otStart (Inactive p) = do
id <- fork p $ exec p
t <- getCurrentTime
return (Active p id t)
otStart active@(Active p _ _) = otKill active >>= otStart
restartOld :: OnlyOne a b -> UTCTime -> IO (OnlyOne a b)
restartOld ot t = if old ot t
then otStart ot
else return ot