{- This file is part of time-cache.
 -
 - Written in 2016 by fr33domlover <fr33domlover@riseup.net>.
 -
 - ♡ Copying is an act of love. Please copy, reuse and share.
 -
 - The author(s) have dedicated all copyright and related and neighboring
 - rights to this software to the public domain worldwide. This software is
 - distributed without any warranty.
 -
 - You should have received a copy of the CC0 Public Domain Dedication along
 - with this software. If not, see
 - <http://creativecommons.org/publicdomain/zero/1.0/>.
 -}

module Data.Time.Cache
    ( TimeGetter
    , mkTimeGetter
    )
where

import Control.AutoUpdate
import Control.Monad.Fix (MonadFix)
import Control.Monad.IO.Class
import Control.Monad.Trans.Class (MonadTrans)
import Data.Text (Text, pack)
import Data.Time.Clock (UTCTime, getCurrentTime)
import Data.Time.Format (TimeLocale, formatTime)
import Data.Time.Units (TimeUnit (toMicroseconds))

type TimeGetter = IO (UTCTime, Text)

mkTimeGetter
    :: TimeUnit t => t -> TimeLocale -> String -> IO TimeGetter
mkTimeGetter interval locale format = mkAutoUpdate defaultUpdateSettings
    { updateFreq   = fromInteger $ toMicroseconds interval
    , updateAction = do
        now <- getCurrentTime
        return (now, pack $ formatTime locale format now)
    }