module HSP.CGI.RunCGI (runCGI) where

import Prelude hiding (catch)

import System.IO (stdout, hPutStr)
import Control.Exception -- (Exception, catch, finally)

import HSP hiding (catch)
import HSP.Env.Request (Request)
import HSP.CGI.CGIEnv (getCGIReq)
import HSP.CGI.NumberGen (mkNumberGen)


runCGI :: HSP XML -> IO ()
runCGI page 
    = (getCGIReq >>= evalCGI page >>= sendCGIResponse)
        `catch` handleError
        `finally` return ()


evalCGI :: HSP XML -> Request -> IO CGIResponse
evalCGI page req = do
	gen <- mkNumberGen
	runHSP page (HSPEnv req gen) >>= return . cgiResponse . renderXML


type CGIResponse = String

cgiResponse :: String -> CGIResponse
cgiResponse body =
	"Content-length: " ++ show (length body) ++
	"\nContent-type: text/html" ++
	"\n\n" ++
	body

sendCGIResponse :: CGIResponse -> IO ()
sendCGIResponse = hPutStr stdout

handleError :: Exception -> IO ()
handleError ex = case ex of
	_ -> sendCGIResponse $ "Error: " ++ show ex