module Database.Persist.TH.Directory
  ( persistDirectoryWith
  ) where

import ClassyPrelude hiding (mapM_, toList)

import Database.Persist.TH (parseReferences)
import Database.Persist.Quasi (PersistSettings)
import Language.Haskell.TH.Syntax

import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import qualified System.IO as SIO

import qualified System.Directory.Tree as DirTree

import Data.Foldable (Foldable(..), mapM_)

persistDirectoryWith :: PersistSettings -> FilePath -> Q Exp
persistDirectoryWith settings dir = do
  files <- runIO . flip DirTree.readDirectoryWith dir $ \fp -> do
    h <- SIO.openFile fp SIO.ReadMode
    SIO.hSetEncoding h SIO.utf8_bom
    Text.hGetContents h
  mapM_ (qAddDependentFile . fst) $ DirTree.zipPaths files
  
  parseReferences settings . Text.intercalate "\n" . toList $ DirTree.dirTree files
