{-# LANGUAGE NamedFieldPuns #-}

module Simplex.Messaging.Server.Expiration
  ( ExpirationConfig (..),
    expireBeforeEpoch,
    showTTL,
  ) where

import Control.Monad.IO.Class
import Data.Int (Int64)
import Data.Time.Clock.System (SystemTime (..), getSystemTime)

data ExpirationConfig = ExpirationConfig
  { -- time after which the entity can be expired, seconds
    ExpirationConfig -> Int64
ttl :: Int64,
    -- interval to check expiration, seconds
    ExpirationConfig -> Int64
checkInterval :: Int64
  }

expireBeforeEpoch :: ExpirationConfig -> IO Int64
expireBeforeEpoch :: ExpirationConfig -> IO Int64
expireBeforeEpoch ExpirationConfig {Int64
ttl :: ExpirationConfig -> Int64
ttl :: Int64
ttl} = Int64 -> Int64 -> Int64
forall a. Num a => a -> a -> a
subtract Int64
ttl (Int64 -> Int64) -> (SystemTime -> Int64) -> SystemTime -> Int64
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SystemTime -> Int64
systemSeconds (SystemTime -> Int64) -> IO SystemTime -> IO Int64
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO SystemTime -> IO SystemTime
forall a. IO a -> IO a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO IO SystemTime
getSystemTime

showTTL :: Int64 -> String
showTTL :: Int64 -> String
showTTL Int64
s
  | Int64
s' Int64 -> Int64 -> Bool
forall a. Eq a => a -> a -> Bool
/= Int64
0 = Int64 -> String
forall a. Show a => a -> String
show Int64
s String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" seconds"
  | Int64
ms' Int64 -> Int64 -> Bool
forall a. Eq a => a -> a -> Bool
/= Int64
0 = Int64 -> String
forall a. Show a => a -> String
show Int64
ms String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" minutes"
  | Int64
hs' Int64 -> Int64 -> Bool
forall a. Eq a => a -> a -> Bool
/= Int64
0 = Int64 -> String
forall a. Show a => a -> String
show Int64
hs String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" hours"
  | Bool
otherwise = Int64 -> String
forall a. Show a => a -> String
show Int64
ds String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" days"
  where
    (Int64
ms, Int64
s') = Int64
s Int64 -> Int64 -> (Int64, Int64)
forall a. Integral a => a -> a -> (a, a)
`divMod` Int64
60
    (Int64
hs, Int64
ms') = Int64
ms Int64 -> Int64 -> (Int64, Int64)
forall a. Integral a => a -> a -> (a, a)
`divMod` Int64
60
    (Int64
ds, Int64
hs') = Int64
hs Int64 -> Int64 -> (Int64, Int64)
forall a. Integral a => a -> a -> (a, a)
`divMod` Int64
24