{-# LANGUAGE OverloadedStrings #-}
module Text.Pandoc.CrossRef.Util.CustomLabels (customLabel) where
import Text.Pandoc.Definition
import Text.Pandoc.CrossRef.Util.Meta
import Text.Numeral.Roman
import qualified Data.Text as T
customLabel :: Meta -> T.Text -> Int -> Maybe T.Text
customLabel meta ref i
| refLabel <- T.takeWhile (/=':') ref
, Just cl <- lookupMeta (refLabel <> "Labels") meta
= mkLabel i (refLabel <> "Labels") cl
| otherwise = Nothing
mkLabel :: Int -> T.Text -> MetaValue -> Maybe T.Text
mkLabel i n lt
| MetaList _ <- lt
, Just val <- toString n <$> getList (i-1) lt
= Just val
| toString n lt == "arabic"
= Nothing
| toString n lt == "roman"
= Just $ toRoman i
| Just (startWith, _) <- T.uncons =<< T.stripPrefix "alpha " (toString n lt)
= Just . T.singleton $ [startWith..] !! (i-1)
| otherwise = error $ "Unknown numeration type: " ++ show lt