{-# LANGUAGE OverloadedStrings #-}

-- |
-- Module      : CLI.Internal
-- License     : BSD3
-- Maintainer  : tbidne@gmail.com
-- Provides a function that parses command keys into their values.
module CLI.Internal
  ( translateCommands,
  )
where

import qualified Data.Map as Map
import qualified Data.Text as T

-- | Returns a list of 'T.Text' commands, potentially transforming a
-- given string via the `Map.Map` legend.
--
-- For a string \(s = s_1,\ldots,s_n\), we split \(s\) by commas then recursively
-- search on each \(s_i\). We stop and return \(s_i\) when it does not exist
-- as a key in the map.
--
-- For example,
--
-- @
--   m = { "cmd1": "one", "cmd2": "two", "all": "cmd1,cmd2,other" }
--   translateCommands m ["all", "blah"] == ["one", "two", "other", "blah"]
-- @
translateCommands :: Map.Map T.Text T.Text -> [T.Text] -> [T.Text]
translateCommands :: Map Text Text -> [Text] -> [Text]
translateCommands mp :: Map Text Text
mp = (Text -> [Text]) -> [Text] -> [Text]
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (Map Text Text -> Text -> [Text]
lineToCommands Map Text Text
mp)

lineToCommands :: Map.Map T.Text T.Text -> T.Text -> [T.Text]
lineToCommands :: Map Text Text -> Text -> [Text]
lineToCommands mp :: Map Text Text
mp line :: Text
line =
  case Text -> Text -> [Text]
T.splitOn "," Text
line of
    [l :: Text
l] ->
      case Text -> Map Text Text -> Maybe Text
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Text
l Map Text Text
mp of
        Just c :: Text
c -> Map Text Text -> Text -> [Text]
lineToCommands Map Text Text
mp Text
c
        Nothing -> [Text
l]
    xs :: [Text]
xs -> [Text]
xs [Text] -> (Text -> [Text]) -> [Text]
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Map Text Text -> Text -> [Text]
lineToCommands Map Text Text
mp