-- |
-- Module:     Network.IHttp.Request
-- Copyright:  (c) 2010 Ertugrul Soeylemez
-- License:    BSD3
-- Maintainer: Ertugrul Soeylemez <es@ertes.de>
-- Stability:  experimental
--
-- Iteratees for requests.

module Network.IHttp.Request
    ( -- * Iteratees
      request,
      requestLine
    )
    where

import Data.ByteString (ByteString)
import Data.Enumerator as E
import Data.Enumerator.List as EL
import Network.IHttp.Header
import Network.IHttp.Parsers
import Network.IHttp.Tools
import Network.IHttp.Types


-- | Get the next full request from a 'netLinesEmpty'-splitted byte
-- stream.  If the request is invalid or the stream ends prematurely an
-- iteratee error is thrown.  The first 'Int' specifies the maximum
-- header content length.  The second 'Int' specifies the maximum number
-- of headers.  Excess data is truncated safely in constant space.

request :: Monad m => Int -> Int -> Iteratee ByteString m Request
request maxHeadLine maxHeaders = do
    req <- requestLine
    headers <- httpHeaders maxHeadLine maxHeaders
    return req { requestHeaders = headers }


-- | Get the next request line from a 'netLinesEmpty'-splitted byte
-- stream.  If the request is invalid or the stream ends prematurely an
-- iteratee error is thrown.

requestLine :: Monad m => Iteratee ByteString m Request
requestLine =
    EL.head
    >>= maybe (throwError $ InvalidRequestError "Premature end of stream") return
    >>= parseIter requestLineP InvalidRequestError