module Byg.Functions.Text
  ( readTextFile
  , saveTextFile
  ) where

import Byg.Types (IsFunctionIO(..), Token(..))
import Byg.DependencyGenerator (DepGenM, TokenableTo(..), toTupleToken,
                            runFunctionIO, runFunctionIO_)
import Byg.DependencyRunner (extractSndTokenAsList)

import Data.Text (Text)
import qualified Data.Text.IO as T

data ReadTextFile = ReadTextFile deriving Show
instance IsFunctionIO ReadTextFile FilePath Text where
  evalFunctionIO ReadTextFile s = T.readFile s
  functionIOReads ReadTextFile s = [s]
  functionIOWrites ReadTextFile  = const (ListToken [])
  functionIOWritesAny ReadTextFile = False

readTextFile :: TokenableTo FilePath a => a -> DepGenM (Token Text)
readTextFile a = runFunctionIO ReadTextFile =<< toToken a


data SaveTextFile = SaveTextFile deriving Show
instance IsFunctionIO SaveTextFile (Text, FilePath) () where
  evalFunctionIO SaveTextFile (t, s) = T.writeFile s t
  functionIOReads SaveTextFile = const []
  functionIOWrites SaveTextFile = extractSndTokenAsList
  functionIOWritesAny SaveTextFile = True

saveTextFile :: (TokenableTo Text a, TokenableTo FilePath b) => a -> b -> DepGenM ()
saveTextFile a b = runFunctionIO_ SaveTextFile =<< toTupleToken a b
