module Heist.Splices.Html where
import           Data.Maybe
import           Data.Text (Text)
import qualified Text.XmlHtml as X
import           Heist.Interpreted.Internal
import           Heist.Internal.Types.HeistState
htmlTag :: Text
htmlTag = "html"
htmlImpl :: Monad n => Splice n
htmlImpl = do
    node <- getParamNode
    children <- runNodeList $ X.childNodes node
    let (heads, mnode) = extractHeads $ node { X.elementChildren = children }
        new (X.Element t a c) = X.Element t a $
            X.Element "head" [] heads : c
        new n = n
    stopRecursion
    return [maybe node new mnode]
extractHeads :: X.Node
             
             -> ([X.Node], Maybe X.Node)
             
             
extractHeads (X.Element t a c)
  | t == "head" = (c, Nothing)
  | otherwise   = (concat heads, Just $ X.Element t a (catMaybes mcs))
  where
    (heads, mcs) = unzip $ map extractHeads c
extractHeads n = ([], Just n)