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

module Handler.Utils.Submission.TH
  ( patternFile
  ) where

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

import System.FilePath.Glob

import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.IO as Text

deriving instance Lift CompOptions

-- $(patternFile compDefault file) :: [System.FilePath.Glob.Pattern]
patternFile :: CompOptions -> FilePath -> ExpQ
patternFile opts file = do
  qAddDependentFile file
  patternStrings <- runIO $ filter (not . isComment) . Text.lines <$> Text.readFile file
  listE $ map (\(Text.unpack -> pat) -> [|compileWith opts pat|]) patternStrings

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