-- import Hack.Contrib.Middleware.Debug
-- import Hack.Contrib.Request (inputs)
-- import Hack.Contrib.Middleware.Inspect
import Hack.Contrib.Middleware.SimpleAccessLogger
-- import Hack.Contrib.Middleware.Lambda
-- import Hack.Contrib.Middleware.Lucky
-- import Hack.Contrib.Middleware.ShowStatus
import Bamboo
import Bamboo.Theme.MiniHTML5
import Hack
import Hack.Contrib.Middleware.BounceFavicon
import Hack.Contrib.Middleware.ContentLength
import Hack.Contrib.Middleware.ContentType
-- import Hack.Contrib.Middleware.ETag
import Hack.Contrib.Middleware.ShowExceptions
import Hack.Contrib.Middleware.Static
import Hack.Contrib.Middleware.URLMap
import Hack.Contrib.Middleware.UTF8Body
-- import Hack.Contrib.Middleware.TokyoCabinetCache
-- import Hack.Middleware.Gzip
import qualified Data.ByteString.Char8 as B
import Hack.Contrib.Request (url)
import Hack.Contrib.Utils
import Hack.Handler.Happstack
import MPS.Env hiding (concat)
import Prelude ()
-- import qualified Hack.Contrib.Middleware.Head as H
import Bamboo.Plugin.Photo
import Bamboo.Plugin.Highlight
import Data.Default
import Data.ByteString.Lazy.Char8 (pack, concat)
import Control.Concurrent.MVar

default_content_type :: String
default_content_type = "text/plain; charset=UTF-8"

stack :: MVar a -> [Middleware]
stack mv = 
  [ dummy_middleware
  
  -- filter
  , bounce_favicon

  -- setup
  --,  parse_multipart
  
  -- log
  , simple_access_logger Nothing
  
  
  -- debug
  -- ,  inspect
  -- ,  debug (\e r -> e.print)
    
  -- completeness

  
  -- debuging
  -- ,  show_status
  
  -- optimization
    -- for fun
  -- ,  lucky
  -- ,  lambda
  
  , show_exceptions Nothing
  , content_length
  , content_type default_content_type
  -- , etag
  , url_map [("", bamboo)]
  ]
  where
    bamboo = use 
      [ bamboo_serve
      -- , tokyocabinet_cache mv "cache.tcb" (url > unescape_uri > B.pack > Just > return)
      , no_rss
      , bamboo_with_theme theme
      ] dummy_app

    bamboo_serve = static (Just "db/public") 
        ["/theme", "/images", "/plugin", "/favicon.ico", "/media"]

    no_rss app' = \env -> do
      if env.path_info.ends_with "rss.xml" 
        then app' env
        else use [html5, utf8_body, photo, highlight] app' env

html5 :: Middleware
html5 app = \env -> do
  r <- app env
  let b = r.body
  return r {body = concat [doc_type, b]}
  where
    doc_type = pack "<!doctype html>\n\n"

-- test_app = \env -> return $ def .set_body (env.inputs.show)

webapp :: MVar a -> Application
webapp mv = use (stack mv) dummy_app

main :: IO ()
main = do
  mv <- newMVar ()
  runWithConfig def {port = 3000} (webapp mv)
  -- run 3000 (webapp mv)
  
