{-# LANGUAGE RecordWildCards #-}

module Network.HTTP2.H2.Config where

import Data.IORef
import Foreign.Marshal.Alloc (free, mallocBytes)
import Network.HTTP.Semantics.Client
import Network.Socket
import Network.Socket.ByteString (sendAll)
import qualified System.TimeManager as T

import Network.HPACK
import Network.HTTP2.H2.Types

-- | Making simple configuration whose IO is not efficient.
--   A write buffer is allocated internally.
--   WAI timeout manger is initialized with 30_000_000 microseconds.
allocSimpleConfig :: Socket -> BufferSize -> IO Config
allocSimpleConfig :: Socket -> Int -> IO Config
allocSimpleConfig Socket
s Int
bufsiz = Socket -> Int -> Int -> IO Config
allocSimpleConfig' Socket
s Int
bufsiz (Int
30 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
1000000)

-- | Making simple configuration whose IO is not efficient.
--   A write buffer is allocated internally.
--   The third argument is microseconds to initialize WAI
--   timeout manager.
allocSimpleConfig' :: Socket -> BufferSize -> Int -> IO Config
allocSimpleConfig' :: Socket -> Int -> Int -> IO Config
allocSimpleConfig' Socket
s Int
bufsiz Int
usec = do
    confWriteBuffer <- Int -> IO (Ptr Word8)
forall a. Int -> IO (Ptr a)
mallocBytes Int
bufsiz
    let confBufferSize = Int
bufsiz
    let confSendAll = Socket -> ByteString -> IO ()
sendAll Socket
s
    confReadN <- defaultReadN s <$> newIORef Nothing
    let confPositionReadMaker = PositionReadMaker
defaultPositionReadMaker
    confTimeoutManager <- T.initialize usec
    confMySockAddr <- getSocketName s
    confPeerSockAddr <- getPeerName s
    return Config{..}

-- | Deallocating the resource of the simple configuration.
freeSimpleConfig :: Config -> IO ()
freeSimpleConfig :: Config -> IO ()
freeSimpleConfig Config
conf = do
    Ptr Word8 -> IO ()
forall a. Ptr a -> IO ()
free (Ptr Word8 -> IO ()) -> Ptr Word8 -> IO ()
forall a b. (a -> b) -> a -> b
$ Config -> Ptr Word8
confWriteBuffer Config
conf
    Manager -> IO ()
T.killManager (Manager -> IO ()) -> Manager -> IO ()
forall a b. (a -> b) -> a -> b
$ Config -> Manager
confTimeoutManager Config
conf