module Route where

import Data.Maybe (fromJust, isJust)
import Data.String (fromString)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T

import Network.Wai

route :: [[Text] -> Maybe Application] -> [Text] -> Application
route routes pathInfo = fromJust $ head $
	filter isJust $ map ($pathInfo) routes

routePath :: Text -> Application -> [Text] -> Maybe Application
routePath path app = doMatch
	where
	doMatch = match c
	match [] [] = Just app
	match (x:xs) (y:ys) | x == y = match xs ys
	match (x:xs) (y:ys) | s":" `T.isPrefixOf` x =
		case match xs ys of
			Just a ->
				let k = T.encodeUtf8 $ fromJust $ T.stripPrefix (s":") x
				    v = Just $ T.encodeUtf8 y in
				Just (
@(Request {queryString = q}) ->
					a (r {queryString = (k,v) : filter ((/=k).fst) q})
				)
			Nothing -> Nothing
	match _ _ = Nothing
	c = filter (not . T.null) $ T.splitOn (s"/") path
	s = fromString
