module Micro.Gateway.Utils
  ( getEpochTime
  , b2t
  , t2b
  , flip'
  , takeKeyFromPath
  , dropKeyFromPath
  ) where

import qualified Data.ByteString    as B (ByteString)
import           Data.Int           (Int64)
import           Data.Text.Encoding (decodeUtf8, encodeUtf8)
import qualified Data.Text.Lazy     as LT (Text, drop, dropWhile, fromStrict,
                                           takeWhile, toStrict)
import           Data.UnixTime
import           Foreign.C.Types    (CTime (..))

getEpochTime :: Num a => IO a
getEpochTime :: IO a
getEpochTime = Int64 -> a
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int64 -> a) -> (UnixTime -> Int64) -> UnixTime -> a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CTime -> Int64
un (CTime -> Int64) -> (UnixTime -> CTime) -> UnixTime -> Int64
forall b c a. (b -> c) -> (a -> b) -> a -> c
. UnixTime -> CTime
toEpochTime (UnixTime -> a) -> IO UnixTime -> IO a
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO UnixTime
getUnixTime
  where un :: CTime -> Int64
        un :: CTime -> Int64
un (CTime t :: Int64
t) = Int64
t

b2t :: B.ByteString -> LT.Text
b2t :: ByteString -> Text
b2t = Text -> Text
LT.fromStrict (Text -> Text) -> (ByteString -> Text) -> ByteString -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Text
decodeUtf8

t2b :: LT.Text -> B.ByteString
t2b :: Text -> ByteString
t2b = Text -> ByteString
encodeUtf8 (Text -> ByteString) -> (Text -> Text) -> Text -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
LT.toStrict

flip' :: (a -> b -> c -> d) -> c -> a -> b -> d
flip' :: (a -> b -> c -> d) -> c -> a -> b -> d
flip' f :: a -> b -> c -> d
f c :: c
c a :: a
a b :: b
b = a -> b -> c -> d
f a
a b
b c
c

takeKeyFromPath :: LT.Text -> LT.Text
takeKeyFromPath :: Text -> Text
takeKeyFromPath = (Char -> Bool) -> Text -> Text
LT.takeWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= '/') (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int64 -> Text -> Text
LT.drop 1

dropKeyFromPath :: Bool -> LT.Text -> LT.Text
dropKeyFromPath :: Bool -> Text -> Text
dropKeyFromPath True  = (Char -> Bool) -> Text -> Text
LT.dropWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= '/') (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int64 -> Text -> Text
LT.drop 1
dropKeyFromPath False = Text -> Text
forall a. a -> a
id