module Network.TinyURL (tinyURL) where

import Network.HTTP
import Network.URI

-- | Use TinyURL to compress a URL.  In the event of a failure, return
-- the original URL.
tinyURL :: String -> IO String
tinyURL url = do
  result <- simpleHTTP request `catch` (const . return $ Left undefined)
  case result of
    Left _ -> return url
    Right response -> return $ rspBody response
  where request = Request { rqURI = uri
                          , rqMethod = GET
                          , rqHeaders = []
                          , rqBody = "" }
        uri = URI { uriScheme = "http:"
                  , uriAuthority = Just $ URIAuth { uriUserInfo = "", uriRegName = "tinyurl.com", uriPort = "" }
                  , uriPath = "/api-create.php"
                  , uriQuery = "?url=" ++ escapeURIString isUnreserved url
                  , uriFragment = "" }
