{-# LANGUAGE
    FlexibleContexts
  , OverloadedStrings
  #-}

module Application where

import Imports hiding ((</>))
import Routes

import System.Directory
import Path.Extended
import qualified Data.Text          as T
import Network.Wai.Session


data AuthRole = NeedsLogin

authorize :: ( MonadApp m
             ) => Request -> [AuthRole] -> m (Response -> Response)
authorize req ss = return id -- no auth roles yet


sessionLayer :: MiddlewareT AppM
sessionLayer app req respond = do
  cfg <- sessionCfg
  env <- ask
  liftMiddleware (`runAppT` env) (sessionMiddleware cfg) app req respond


-- * Middlewares

securityLayer :: MonadApp m => MiddlewareT m
securityLayer = extractAuth authorize routes

loginLayer :: MonadApp m => MiddlewareT m
loginLayer = route loginRoutes

contentLayer :: MonadApp m => MiddlewareT m
contentLayer = route routes

staticLayer :: MonadApp m => MiddlewareT m
staticLayer app req respond = do
    let fileRequested = T.unpack . T.intercalate "/" $ pathInfo req
    basePath <- envStatic <$> ask
    let file = toFilePath basePath ++ fileRequested
    fileExists <- liftIO (doesFileExist file)
    if fileExists
        then respond $ responseFile status200 [] file Nothing
        else app req respond

defApp :: Application
defApp _ respond =
  respond $ textOnlyStatus status404 "Not Found! :("
