module Text.Roundtrip.Xml.Combinators (

    eatWhiteSpace, xmlElem, xmlAttr, xmlFixedAttr, xmlText, xmlString

) where

import Prelude hiding ((.))

import Control.Category ((.))
import Data.Char (isSpace)
import qualified Data.Text as T

import Data.XML.Types (Name)
import Safe (readMay)

import Text.Roundtrip.Classes
import Text.Roundtrip.Combinators
import Text.Roundtrip.Xml.Classes

import Control.Isomorphism.Partial

eatWhiteSpace :: XmlSyntax d => d ()
eatWhiteSpace = ignore T.empty . subset "allIsSpace" (T.all isSpace) <$> xmlText <|> pure ()

xmlElem :: XmlSyntax x => Name -> x a -> x a
xmlElem name children =
    xmlBeginElem name *> children <* xmlEndElem name

xmlAttr :: XmlSyntax x => Name -> Iso T.Text a -> x a
xmlAttr name p = p <$> xmlAttrValue name

xmlFixedAttr :: XmlSyntax x => Name -> T.Text -> x ()
xmlFixedAttr name value = fixedValue value <$> xmlAttrValue name

xmlText :: XmlSyntax d => d T.Text
xmlText = optionalWithDefault T.empty xmlTextNotEmpty

xmlString :: XmlSyntax d => d String
xmlString = textStringIso <$> xmlText