{-# LANGUAGE TypeFamilies #-}
module RepositoryOnMemory where

import qualified Data.Map as M
import Control.Concurrent.MVar
import Entity
import Repository

data Memory k e = Memory (MVar (M.Map k e))

instance (Ord k, Entity e, EKey e ~ k) => Repository (Memory k e) where
  type RKey (Memory k e) = k
  type REntity (Memory k e) = e

  resolve (Memory m) k = fmap (M.lookup k) (readMVar m)
  store (Memory m) k e = do
    if getKey e /= k 
      then error "key does not match"
      else modifyMVar_ m (\m' -> return (M.insert k e m'))

newRepositoryOnMemory :: IO (Memory k e)
newRepositoryOnMemory = fmap Memory (newMVar M.empty)


