module Text.Domplate.Context where
import qualified Data.Text as T
import qualified Data.HashMap.Strict as M
import Data.ByteString (ByteString)
import Data.Yaml
import Data.Monoid
type Key = T.Text
newtype Context = Ctx (M.HashMap Key Value)
deriving Show
instance Monoid Context where
mempty = empty
mappend (Ctx a) (Ctx b) = Ctx $ M.union a b
mconcat = Ctx . M.unions . map (\(Ctx ctx) -> ctx)
typeOf :: Value -> String
typeOf (String _) = "text"
typeOf (Number _) = "number"
typeOf (Bool _) = "boolean"
typeOf (Array _) = "array"
typeOf (Object _) = "object"
typeOf (Null) = "null"
fromJSON :: Value -> Context
fromJSON (Object o) = Ctx o
fromJSON _ = error "Tried to make a context out of a non-object!"
fromList :: [(Key, Value)] -> Context
fromList = Ctx . M.fromList
toValue :: Context -> Value
toValue (Ctx ctx) = Object ctx
add :: Key -> Value -> Context -> Context
add k v (Ctx ctx) = Ctx $ M.insert k v ctx
remove :: Key -> Context -> Context
remove k (Ctx ctx) = Ctx $ M.delete k ctx
empty :: Context
empty = Ctx M.empty
lookup :: Key -> Context -> Maybe Value
lookup key (Ctx m) = M.lookup key m
size :: Context -> Int
size (Ctx m) = M.size m
parseContext :: ByteString -> Either String Context
parseContext bs = do
val <- decodeEither bs
case val of
Object ctx -> return $ Ctx ctx
_ -> Left "Decoded value was not an object!"