import Hack
import Web.Encodings
import Hack.Handler.SimpleServer
import qualified Data.ByteString.Lazy.Char8 as L
import Data.Maybe

main = run 3000 app

app env =
    case pathInfo env of
        "/" -> return $ Response 200 [("Content-Type", "text/html")] $
                L.pack $ concat
                    [ "<form method='post' action='/upload' "
                    , "enctype='multipart/form-data'>"
                    , "<input type='file' name='file'>"
                    , "<input type='submit>"
                    , "</form>"
                    ]
        "/upload" -> do
            let ct = fromJust $ lookup "Content-Type" $ http env
            let cl = fromJust $ lookup "Content-Length" $ http env
            let (_, [(_, FileInfo _ ct' content)]) =
                    parsePost ct cl $ hackInput env
            let filename = "test.output"
            L.writeFile filename content
            let ct'' = L.unpack ct'
            Response 200 [("Content-Type", ct'')] `fmap` L.readFile filename
