{-# LANGUAGE NoMonomorphismRestriction#-}
{-# LANGUAGE QuasiQuotes #-}

module Hack.Contrib.SimpleRouter where

import Hack
import Hack.Utils
import List (find)
import Prelude hiding ((.), (^), (>))
import MPS

type RoutePath = (String, Application)

route :: [RoutePath] -> MiddleWare
route h _ = \env ->
  let path             = env.path_info
      script           = env.script_name
      mod_env location = env 
        { script_name  = script ++ location
        , path_info    = path.drop (location.length)
        }
  in
  case h.find (fst > flip starts_with path) of
    Nothing -> not_found [$here|Not Found: #{path}|]
    Just (location, app) -> app (mod_env location)