module Periodic.Node
  ( Nid (..)
  , NodeEnv
  , NodeT
  , SessionT
  , SessionEnv
  , SessionEnv1
  , NodeEnvList
  , runNodeT
  , sessionGen
  , defaultSessionHandler
  ) where

import           Metro.IOHashMap   (IOHashMap)
import qualified Metro.Node        as M (NodeEnv1, NodeT, runNodeT1)
import qualified Metro.Session     as M (SessionEnv, SessionEnv1, SessionT,
                                         getSessionId)
import           Periodic.Types    (Msgid (..), Nid (..), Packet, msgidLength)
import           System.Entropy    (getEntropy)
import           System.Log.Logger (errorM)
import           UnliftIO          (MonadIO, liftIO)

type NodeEnv u rpkt = M.NodeEnv1 u Nid Msgid (Packet rpkt)

type NodeT u rpkt = M.NodeT u Nid Msgid (Packet rpkt)

type SessionT u rpkt = M.SessionT u Nid Msgid (Packet rpkt)

type SessionEnv u rpkt = M.SessionEnv u Nid Msgid (Packet rpkt)
type SessionEnv1 u rpkt = M.SessionEnv1 u Nid Msgid (Packet rpkt)

sessionGen :: IO Msgid
sessionGen :: IO Msgid
sessionGen = ByteString -> Msgid
Msgid (ByteString -> Msgid) -> IO ByteString -> IO Msgid
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Int -> IO ByteString
getEntropy Int
msgidLength

type NodeEnvList u rpkt tp = IOHashMap Nid (NodeEnv u rpkt tp)

runNodeT :: Monad m => NodeEnv u rpkt tp -> NodeT u rpkt tp m a -> m a
runNodeT :: NodeEnv u rpkt tp -> NodeT u rpkt tp m a -> m a
runNodeT  = NodeEnv u rpkt tp -> NodeT u rpkt tp m a -> m a
forall u nid k rpkt tp (m :: * -> *) a.
NodeEnv1 u nid k rpkt tp -> NodeT u nid k rpkt tp m a -> m a
M.runNodeT1

defaultSessionHandler :: MonadIO m => SessionT u rpkt tp m ()
defaultSessionHandler :: SessionT u rpkt tp m ()
defaultSessionHandler = do
  Msgid
pid <- SessionT u Nid Msgid (Packet rpkt) tp m Msgid
forall (m :: * -> *) u nid k rpkt tp.
Monad m =>
SessionT u nid k rpkt tp m k
M.getSessionId
  IO () -> SessionT u rpkt tp m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> SessionT u rpkt tp m ())
-> IO () -> SessionT u rpkt tp m ()
forall a b. (a -> b) -> a -> b
$ String -> String -> IO ()
errorM "Periodic.Node" (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ "Session [" String -> String -> String
forall a. [a] -> [a] -> [a]
++ Msgid -> String
forall a. Show a => a -> String
show Msgid
pid String -> String -> String
forall a. [a] -> [a] -> [a]
++ "] not found."