-- SPDX-FileCopyrightText: 2022 Gregor Kleen <gregor.kleen@ifi.lmu.de>
--
-- SPDX-License-Identifier: AGPL-3.0-or-later

{-# OPTIONS_GHC -fno-warn-orphans #-}

module System.FilePath.Glob.TH
  ( patternFile, patternFile'
  ) where

import ClassyPrelude.Yesod
import Language.Haskell.TH
import Language.Haskell.TH.Syntax (qAddDependentFile, Lift(..), unsafeTExpCoerce)

import System.FilePath.Glob

import qualified Data.Text as Text
import qualified Data.Text.IO as Text

import qualified Data.Map.Strict as Map

deriving instance Lift CompOptions

patternFile' :: CompOptions -> FilePath -> TExpQ (Map Text Pattern)
patternFile' opts file = do
  qAddDependentFile file
  patternStrings <- runIO $ filter (not . isComment) . Text.lines <$> Text.readFile file
  unsafeTExpCoerce . appE [e|Map.fromList|] . listE $ map (\pat'@(Text.unpack -> pat) -> [e|(pat', compileWith opts pat)|]) patternStrings

patternFile :: CompOptions -> FilePath -> TExpQ [Pattern]
patternFile opts file = [||Map.elems $$(patternFile' opts file)||]

isComment :: Text -> Bool
isComment line = or
  [ commentSymbol `Text.isPrefixOf` Text.stripStart line
  , Text.null $ Text.strip line
  ]
  where
    commentSymbol = "$#"
