import Data.Maybe
import Network.HTTP
import Network.URI
import qualified Codec.Binary.Base64.String as Base64
import qualified Codec.Binary.UTF8.String as C

data Account = Account {tId::String
                       ,tPass::String}
               deriving Show

habot :: Account
habot = Account "habot" "haskellworld"

twitterURIbase :: String
twitterURIbase = "http://twitter.com/"

toUri :: String -> URI
toUri url = fromJust $ parseURI url

authHeader :: Account -> Header
authHeader acc
 = Header HdrAuthorization basic
   where
     basic = "Basic " ++ Base64.encode str
     str = (tId acc ++ ":" ++ tPass acc)

twGetReq,twPostReq :: String -> Account -> Request String
(twGetReq,twPostReq) = (gen GET, gen POST)
  where
    toUri' path = toUri $ twitterURIbase ++ path
    gen meth path acc
        = Request (toUri' path) meth [authHeader acc] ""

encodeQPs :: [(String, String)] -> String
encodeQPs qps = urlEncodeVars $ map toUtf8 qps
  where
    toUtf8 (k,v)
       = (C.encodeString k,C.encodeString v)

verify_credentials :: Account -> Request String
verify_credentials acc = twGetReq path acc
  where
    path = "account/verify_credentials.json"

update :: String -> Account -> Request String
update msg acc
 = twPostReq ("statuses/update.json?"++m) acc
    where m = encodeQPs [("status", msg)]

api :: Request String -> IO ()
api req = do Right res <- simpleHTTP req
             print $ rspHeaders res
             print $ rspBody res

