{-# LANGUAGE FlexibleInstances #-}

-- | Provides in-haskell implementations for some standard functions
module System.Chatty.Commands where

import Text.Chatty.Printer
import Text.Chatty.Scanner
import Text.Chatty.Interactor
import Text.Chatty.Finalizer
import Text.Chatty.Expansion
import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.IO.Class
import System.IO
import System.Directory
import System.Posix.Files

-- | Like 'cat' on the command line. Accepts a list of filenames. Simple pass-through, if none are provided.
cat :: (MonadScanner m, MonadPrinter m, MonadIO m,Functor m,MonadFinalizer m) => [String] -> m ()
cat [] = mscanL >>= mprint
cat [f] = cat [] .<. f
cat (f:fs) = cat [f] >> cat fs

-- | Like 'cat', but reverses the line order.
tac :: (MonadFinalizer m,MonadScanner m, MonadPrinter m, MonadIO m,Functor m) => [String] -> m ()
tac [] = mscanL >>= (mprint . unlines . reverse . lines)
tac fs = cat fs .|. tac []

-- | Pass-through, simultanously writing all input to a given file.
tee :: (MonadScanner m, MonadPrinter m, MonadIO m, Functor m) => String -> m ()
tee f = do
  s <- mscanL
  mprint s .>. f
  mprint s

-- | Prints the given string, after expanding it.
echo :: (MonadPrinter m,MonadExpand m) => String => m ()
echo = mprintLn <=< expand

-- | Mode for 'wc'.
data WcMode = CountChars | CountLines | CountWords

-- | Count characters, lines or words of the input.
wc :: (MonadScanner m, MonadPrinter m, MonadIO m, Functor m) => WcMode -> m ()
wc CountChars = mscanL >>= (mprint . show . length) >> mprint "\n"
wc CountLines = mscanL >>= (mprint . show . length . lines) >> mprint "\n"
wc CountWords = mscanL >>= (mprint . show . length . words) >> mprint "\n"

-- | Change to given directory.
cd :: MonadIO m => String -> m ()
cd = liftIO . setCurrentDirectory

-- | Print current working directory.
pwd :: (MonadIO m,MonadPrinter m) => m ()
pwd = liftIO getCurrentDirectory >>= mprintLn

-- | List directory contents of the given directories (current one, if empty list).
ls :: (MonadIO m,MonadPrinter m) => [String] -> m ()
ls [] = liftIO (getDirectoryContents ".") >>= (mprint . unlines)
ls [p] = do
  fs <- liftIO $ getFileStatus p
  when (isDirectory fs) $
    liftIO (getDirectoryContents p) >>= (mprint . unlines)
  when (isRegularFile fs) $
    mprintLn p
ls (p:ps) = ls [p] >> ls ps

-- | Filters only the first n lines of the input.
head :: (MonadScanner m,MonadPrinter m,MonadIO m,Functor m) => Int -> m ()
head n = mscanL >>= (mprint . unlines . take n . lines)

-- | FIlters only the last n lines of the input.
tail :: (MonadScanner m,MonadPrinter m,MonadIO m,Functor m) => Int -> m ()
tail n = mscanL >>= (mprint . unlines . reverse . take n . reverse . lines)