{-# LANGUAGE RecordWildCards #-}

module Network.Shelob.Request where

import           Data.Monoid ((<>))
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Builder as B
import qualified Data.Foldable as F

import           Network.Shelob.Types

crlf :: B.Builder
crlf = B.char7 '\13' <> B.char7 '\10'

pRequest :: Request -> B.ByteString
pRequest Request { .. } = B.toLazyByteString body
  where body = pMethod requestMethod <> B.char7 ' ' <>
               B.byteString requestPath <>
               B.byteString " HTTP/1.1" <>
               crlf <>
               F.foldMap pHeader requestHeaders <>
               crlf <>
               B.byteString requestBody

pMethod :: Method -> B.Builder
pMethod m = B.byteString $ case m of
  MGet      -> "GET"
  MHead     -> "HEAD"
  MPost     -> "POST"
  MPut      -> "PUT"
  MDelete   -> "DELETE"
  MTrace    -> "TRACE"
  MOptions  -> "OPTIONS"
  MConnect  -> "CONNECT"
  MPatch    -> "PATCH"
  MOther bs -> bs
pHeader :: Header -> B.Builder
pHeader (HContentLength v) =
  B.byteString "Content-Length: " <>
  B.intDec v <> crlf
pHeader (Header k v) =
  B.byteString k <> B.char7 ':' <> B.char7 ' ' <>
  B.byteString v <> crlf
