-- #prune

-- |Manipulation of HTTP version string.
module Network.HTTP.Lucu.HttpVersion
    ( HttpVersion(..)
    , httpVersionP
    , hPutHttpVersion
    )
    where

import qualified Data.ByteString.Char8 as C8
import           Network.HTTP.Lucu.Parser
import           Prelude hiding (min)
import           System.IO

-- |@'HttpVersion' major minor@ represents \"HTTP\/major.minor\".
data HttpVersion = HttpVersion !Int !Int
                   deriving (Eq)

instance Show HttpVersion where
    show (HttpVersion maj min) = "HTTP/" ++ show maj ++ "." ++ show min

instance Ord HttpVersion where
    (HttpVersion majA minA) `compare` (HttpVersion majB minB)
        | majA > majB = GT
        | majA < majB = LT
        | minA > minB = GT
        | minA < minB = LT
        | otherwise   = EQ


httpVersionP :: Parser HttpVersion
httpVersionP = do string "HTTP/"
                  major <- many1 digit
                  char '.'
                  minor <- many1 digit
                  return $ HttpVersion (read' major) (read' minor)
    where
      read' "1" = 1 -- この二つが
      read' "0" = 0 -- 壓倒的に頻出する
      read' s   = read s


hPutHttpVersion :: Handle -> HttpVersion -> IO ()
hPutHttpVersion h (HttpVersion maj min)
    = h `seq`
      do C8.hPut  h (C8.pack "HTTP/")
         hPutStr  h (show maj)
         hPutChar h '.'
         hPutStr  h (show min)