-- Peer thread implementation

-- | Spawns a new peer thread
--
-- Requests for fetching new blocks can be sent to the channel and those blocks
-- will be eventually written to the writer channel.
initPeerThread :: Peer -> AvailabilityChannel -> DataChannel -> IO (ThreadId, PeerThread)
initPeerThread p availChan dataChan = do
    putStrLn $ "Spawning peer thread for " ++ show p
    requestChan <- newChan :: IO (Chan Integer)
    let pt = PeerThread p availChan requestChan dataChan
    -- bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
    tid <- forkIO $ bracket (initialize pt) cleanup action
    return (tid, pt)
  where
      -- | Spawns two threads to talk peer protocol and download requested blocks
      action :: PeerThread -> IO ()
      action pt = do
          _ <- forkIO $ loop pt
          _ <- forkIO $ downloader pt
          return ()

-- |Initialize module. Resources allocated here must be cleaned up in cleanup
initPeerThread :: Peer -> AvailabilityChannel -> DataChannel -> IO (ThreadId, PeerThread)
initPeerThread p availChan dataChan = do
    putStrLn $ "Spawning peer thread for " ++ show p
    requestChan <- newChan :: IO (Chan Integer)
    let pt = PeerThread p availChan requestChan dataChan
    -- bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
    tid <- forkIO $ bracket (initialize pt) cleanup action
    return (tid, pt)
  where
      -- | Spawns two threads to talk peer protocol and download requested blocks
      action :: PeerThread -> IO ()
      action pt = do
          _ <- forkIO $ loop pt
          _ <- forkIO $ downloader pt
          return ()

-- |Initialize module. Resources allocated here must be cleaned up in cleanup
initPeerThread p availChan dataChan = do
    putStrLn $ "Spawning peer thread for " ++ show p
    requestChan <- newChan :: IO (Chan Integer)
    let pt = PeerThread p availChan requestChan dataChan
    -- bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
    tid <- forkIO $ bracket (initialize pt) cleanup action
    return (tid, pt)
  where
      -- | Spawns two threads to talk peer protocol and download requested blocks
      action :: PeerThread -> IO ()
      action pt = do
          _ <- forkIO $ loop pt
          _ <- forkIO $ downloader pt
          return ()

-- |Initialize module. Resources allocated here must be cleaned up in cleanup