{-# LANGUAGE CPP               #-}
{-# LANGUAGE OverloadedStrings #-}
module Text.Inflections.Transliterate
    ( transliterate
    , transliterateCustom )
where
import Data.Char (isAscii)
import Data.Text (Text)
import Text.Inflections.Data
import qualified Data.HashMap.Strict as M
import qualified Data.Text           as T
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
transliterate :: Text -> Text
transliterate = transliterateCustom "?" defaultTransliterations
transliterateCustom
  :: String            
  -> Transliterations  
  -> Text              
  -> Text              
transliterateCustom replacement m txt = T.unfoldr f ("", txt)
  where
    f ("", t) = uncurry g <$> T.uncons t
    f (x:xs, t) = Just (x, (xs, t))
    g x xs =
      if isAscii x
        then (x, ("", xs))
        else
          case M.lookupDefault replacement x m of
            ""     -> ('?', ("",xs))
            (y:ys) -> (y,   (ys,xs))