module Haskore.Basic.Timer where

import System.Time(ClockTime(TOD))
import Control.Monad(replicateM_)

import qualified Numeric.NonNegative.Wrapper as NonNeg
-- import Numeric.NonNegative.Class ((-|))


data T = Cons {
     getClockTime :: IO ClockTime,
     waitInt      :: NonNeg.Int -> IO (),
     resolution   :: NonNeg.Integer
  }

getTime :: T -> IO Integer
getTime timer =
   fmap (clockTimeToWaitTime (resolution timer)) $
   getClockTime timer

clockTimeToWaitTime :: NonNeg.Integer -> ClockTime -> Integer
clockTimeToWaitTime res0 (TOD secs picos) =
   let res = NonNeg.toNumber res0
   in  secs * res + div (picos * res) (10^(12::Int))

getTimeSeconds :: Fractional time =>
   T -> IO time
getTimeSeconds timer =
   fmap clockTimeToSeconds $
   getClockTime timer

clockTimeToSeconds :: Fractional time => ClockTime -> time
clockTimeToSeconds (TOD secs picos) =
   fromInteger secs + fromInteger picos * 1e-12

{-
The range of 32 bit Ints does not suffice for waiting an hour
measured in microseconds.
-}
wait :: T -> NonNeg.Integer -> IO ()
wait timer time =
   let blockSize = maxBound
       {- Negative delays can occur if multiple events should be scheduled
          at the same time, but are processed subsequently.
          In this case we just not wait but hope to return to schedule
          as time goes by. -}
       (reps,remainder) = divMod (max 0 time) (fromIntegral blockSize)
   in  -- putStrLn ("wait Integer " ++ show time) >>
       -- print (reps,remainder) >>
       --  if time<0
       --    then error "Timer.wait: can't wait a negative time"

       -- I hope that 'reps' will always fit in Int range
       replicateM_ (fromIntegral reps) (waitInt timer blockSize) >>
       waitInt timer (fromIntegral remainder)

waitUntil :: T -> Integer -> IO ()
waitUntil timer time =
   do tcur <- getTime timer
      wait timer (NonNeg.fromNumberClip (time - tcur))

waitUntilSeconds :: (RealFrac time) =>
   T -> time -> IO ()
waitUntilSeconds timer time =
   waitUntil timer (floor (time * fromIntegral (resolution timer)))
