module Utils.Csv
  ( pathPieceCsv
  , (.:??)
  ) where

import ClassyPrelude hiding (lookup)
import Data.Csv hiding (Name)
  
import Language.Haskell.TH (Name)
import Language.Haskell.TH.Lib


pathPieceCsv :: Name -> DecsQ
pathPieceCsv (conT -> t) =
  [d|
    instance ToField $(t) where
      toField = toField . toPathPiece
    instance FromField $(t) where
      parseField = maybe (fail "Could not unmarshal from PathPiece") return . fromPathPiece <=< parseField
  |]


(.:??) :: FromField (Maybe a) => NamedRecord -> ByteString -> Parser (Maybe a)
m .:?? name = lookup m name <|> return Nothing
