{-# LANGUAGE ExistentialQuantification, RankNTypes, Rank2Types, Safe #-}

{-
  This module is part of Chatty.
  Copyleft (c) 2014 Marvin Cohrs

  All wrongs reversed. Sharing is an act of love, not crime.
  Please share Antisplice with everyone you like.

  Chatty is free software: you can redistribute it and/or modify
  it under the terms of the GNU Affero General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  Chatty is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License
  along with Chatty. If not, see <http://www.gnu.org/licenses/>.
-}

module Text.Chatty.Expansion.Vars where

import Control.Applicative
import Control.Arrow
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import System.Environment --hiding (getEnv)
--import System.Posix.Env (getEnv, setEnv)
import Text.Chatty.Expansion

-- | Some environment variable
data EnvVar = NotSet                       -- ^ Not set.
            | Literal String               -- ^ An embeddable string.
            | forall a.Show a => Scalar a  -- ^ Something we can show.
            | Array [EnvVar]               -- ^ Array of that

instance Show EnvVar where
  show (Scalar s) = show s
  show (Literal s) = s
  show (Array ps) = unwords $ map show ps
  show NotSet = ""


-- | Environment storage and variable expander.
newtype ExpanderT m a = Expander {
    runExpanderT :: [(String,EnvVar)] -> m (a,[(String,EnvVar)])
  }

instance Monad m => Monad (ExpanderT m) where
  return a = Expander $ \vs -> return (a,vs)
  (Expander e) >>= f = Expander $ \vs -> do (a,vs') <- e vs; runExpanderT (f a) vs'

instance MonadTrans ExpanderT where
  lift m = Expander $ \vs -> do a <- m; return (a,vs)

instance MonadIO m => MonadIO (ExpanderT m) where
  liftIO = lift . liftIO

instance Monad m => Functor (ExpanderT m) where
  fmap f a = Expander $ \vs -> do (a',vs') <- runExpanderT a vs; return (f a',vs')

instance Monad m => Applicative (ExpanderT m) where
  (<*>) = ap
  pure = return

-- | Run this function inside a blank environment.
localEnvironment :: Functor m => ExpanderT m a -> m a
localEnvironment m = fmap fst $ runExpanderT m []

-- | Run this function in a locally modifiable, but not exported environment
forkEnvironment :: (Functor m,Monad m,MonadIO m) => ExpanderT m a -> m a
forkEnvironment m = do
  es <- liftIO getEnvironment
  fmap fst $ runExpanderT m $ fmap (second Literal) es

-- | Export this local environment.
exportAll :: (Monad m,MonadIO m) => ExpanderT m ()
exportAll = Expander $ \vs -> do
  liftIO $ forM_ vs $ \(k,v) -> setEnv k (show v)
  return ((),vs)

instance ChExpand IO where
  expand = expandVars

instance ChExpand m => ChExpand (ExpanderT m) where
  expand = lift . expand <=< expandVars

-- | Expand $variables
expandVars :: (Monad m,Functor m,ChExpanderEnv m) => String -> m String
expandVars [] = return []
expandVars ('\\':'$':ss) = do r <- expandVars ss; return ('$':r)
expandVars ('$':'{':ss) =
  let nm = takeBrace 0 ss
      rm = drop (length nm + 1) ss
      takeBrace :: Int -> String -> String
      takeBrace 0 ('}':ss) = ""
      takeBrace n ('}':ss) = '}' : takeBrace (n-1) ss
      takeBrace n ('{':ss) = '{' : takeBrace (n+1) ss
      takeBrace n (s:ss) = s : takeBrace n ss
  in do
    v <- fmap show $ mgetv nm
    r <- expandVars rm
    return (v++r)
expandVars ('$':ss) =
  let (nm,rm) = (takeWhile isAnum &&& dropWhile isAnum) ss
  in do
    v <- fmap show $ mgetv nm
    r <- expandVars rm
    return (v++r)
expandVars (s:ss) = do ss' <- expandVars ss; return (s:ss')

-- | Is alphanumeric?
isAnum = (`elem` (['a'..'z']++['A'..'Z']++"_"++['0'..'9']))

-- | Typeclass for all environment storages.
class Monad ee => ChExpanderEnv ee where
  -- | Get environment variable
  mgetv :: String -> ee EnvVar
  -- | Put environment variable
  mputv :: String -> EnvVar -> ee ()

instance Monad m => ChExpanderEnv (ExpanderT m) where
  mgetv s = Expander $ \vs -> return $
    case filter ((==s).fst) vs of
      [] -> (NotSet,vs)
      ((_,v):_) -> (v,vs)
  mputv k v = Expander $ \vs -> return ((),(k,v):filter ((/=k).fst) vs)

instance ChExpanderEnv IO where
  mgetv = fmap Literal . getEnv
  mputv k v = setEnv k (show v)