module Data.HMemDb.RefContainer (RefContainer(insRef, delRef)) where
import Control.Compose (Id(Id))
import Data.Foldable (Foldable)
import Data.Set (Set, delete, empty, insert, singleton)
import Data.HMemDb.References (Ref)
-- | This class is a closed one; the user is not supposed to create new instances.
-- It allows treating unique and non-unique keys in the same way.
class Foldable s => RefContainer s where
    insRef :: Ref r -> Maybe (s (Ref r)) -> Maybe (s (Ref r))
    delRef :: Ref r -> s (Ref r) -> Maybe (s (Ref r))
instance RefContainer Id where
    insRef ref Nothing = Just $ Id ref
    insRef _ (Just _) = Nothing
    delRef _ _ = Nothing
instance RefContainer Set where
    insRef ref Nothing = Just $ singleton ref
    insRef ref (Just s) = Just $ insert ref s
    delRef ref s =
        let s' = delete ref s
        in if s' == empty then Nothing else Just s'