{-# options_haddock prune #-}
-- |Yank Logic, Internal
module Helic.Yank where

import qualified Data.Text.IO as Text
import Polysemy.Chronos.Time (ChronosTime)
import Polysemy.Http (Manager)
import Polysemy.Log (Log)

import Helic.Data.AgentId (AgentId (AgentId))
import qualified Helic.Data.Event as Event
import Helic.Data.Host (Host (Host))
import Helic.Data.InstanceName (InstanceName)
import Helic.Data.NetConfig (NetConfig (NetConfig))
import Helic.Data.YankConfig (YankConfig (YankConfig))
import Helic.Net.Api (defaultPort)
import Helic.Net.Client (sendTo)

-- |Send an event to the server.
yank ::
  Members [Reader InstanceName, ChronosTime, Manager, Log, Race, Error Text, Embed IO] r =>
  NetConfig ->
  YankConfig ->
  Sem r ()
yank :: NetConfig -> YankConfig -> Sem r ()
yank (NetConfig Maybe Int
port Maybe Timeout
timeout Maybe [Host]
_) (YankConfig Maybe Text
agent) = do
  Text
text <- IO Text -> Sem r Text
forall (m :: * -> *) (r :: EffectRow) a.
Member (Embed m) r =>
m a -> Sem r a
embed (Handle -> IO Text
Text.hGetContents Handle
stdin)
  Event
event <- AgentId -> Text -> Sem r Event
forall (r :: EffectRow).
Members '[ChronosTime, Reader InstanceName] r =>
AgentId -> Text -> Sem r Event
Event.now (Text -> AgentId
AgentId (Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe Text
"cli" Maybe Text
agent)) Text
text
  Maybe Timeout -> Host -> Event -> Sem r ()
forall (r :: EffectRow).
Members '[Manager, Log, Race, Error Text, Embed IO] r =>
Maybe Timeout -> Host -> Event -> Sem r ()
sendTo Maybe Timeout
timeout (Text -> Host
Host [exon|localhost:#{show (fromMaybe defaultPort port)}|]) Event
event