module Network.PGI.Handlers where

import Network.PGI
import TNET
import Control.Monad (liftM)

constHandler :: (TNET a) => a -> Handler
constHandler v = const (return tv)
  where tv = toTNET v

constHandlerM :: (TNET a) => IO a -> Handler
constHandlerM iv = const (liftM toTNET iv)

makeHandler :: (TNET a, TNET b) => (a -> b) -> Handler
makeHandler f raw_req =
  case fromTNET raw_req of
    Nothing -> decodeError raw_req
    Just req -> return . toTNET $ f req

makeHandlerM :: (TNET a, TNET b) => (a -> IO b) -> Handler
makeHandlerM f raw_req =
  case fromTNET raw_req of
    Nothing -> decodeError raw_req
    Just req -> liftM toTNET $ f req

bodyData :: (TNET a) => a -> TValue
bodyData v = dict [ "body_data" .= v ]

decodeError tval = error $ unlines [ "Request was not the right type: "
                                   , (show . encode) tval
                                   ]