{-# LANGUAGE 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.History where

import Prelude hiding (id,(.))
import Control.Applicative
import Control.Arrow
import Control.Category (id,(.))
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Text.Chatty.Expansion

newtype HistoryT m a = History {
    runHistoryT :: [String] -> m (a,[String])
  }

instance Monad m => Monad (HistoryT m) where
  return a = History $ \s -> return (a,s)
  (History h) >>= f = History $ \s -> do (a,s') <- h s; runHistoryT (f a) s'

instance MonadTrans HistoryT where
  lift m = History $ \s -> do a <- m; return (a,s)

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

instance Monad m => Functor (HistoryT m) where
  fmap f a = History $ \s -> do (a',s') <- runHistoryT a s; return (f a',s')

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

class Monad he => ChHistoryEnv he where
  mcounth :: he Int
  mgeth :: Int -> he String
  mputh :: String -> he ()

instance Monad m => ChHistoryEnv (HistoryT m) where
  mcounth = History $ runKleisli (arr length &&& id)
  mgeth i
    | i <= 0 = let j = -i in History $ runKleisli (arr (!!j) &&& id)
    | otherwise = History . runKleisli $ arr ((!!i).reverse &&& id)
  mputh s = History . runKleisli $ arr (const () &&& (s:))

expandHist :: ChHistoryEnv h => String -> h String
expandHist [] = return []
expandHist ('!':ss) =
  let (nm,rm) = (takeWhile isNum &&& dropWhile isNum) ss
      isNum a = elem a ['0'..'9'] || (a=='-')
  in case nm of
    [] -> do
      ss' <- expandHist ss
      return ('!':ss')
    _ -> do
      hs <- expandHist rm
      h <- mgeth $ read nm
      return (h++hs)
expandHist (s:ss) = do ss' <- expandHist ss; return (s:ss')

instance ChExpand m => ChExpand (HistoryT m) where
  expand = lift . expand <=< expandHist

withHistory :: Monad m => HistoryT m a -> m a
withHistory = liftM fst . flip runHistoryT []