{-# 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/>.
-}

-- | Provides a typeclass for process spawning.
module System.Chatty.Spawn where

import Text.Chatty.Finalizer
import Text.Chatty.Printer
import Text.Chatty.Scanner
import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class
import System.Exit
import System.IO
import qualified System.Process as P

-- | Class for all (real or pseudo) process-spawning monads.
class Monad m => ChSpawn m where
  -- | Spawn process
  mspw :: String -> [String] -> Either Handle String -> m (Int,String,[Handle])
  -- | Accept handle as input?
  mah :: String -> m Bool

instance ChSpawn IO where
  mspw pn as (Left h) = do
    (_, Just hout, _, ph) <- P.createProcess (P.proc pn as){
      P.std_in = P.UseHandle h,
      P.std_out = P.CreatePipe }
    so <- hGetContents hout
    ec <- P.waitForProcess ph
    return (case ec of
               ExitSuccess -> 0
               ExitFailure i -> i,
            so, [hout])
  mspw pn as (Right si) = do
    (ec,so,_) <- P.readProcessWithExitCode pn as si
    return (case ec of
               ExitSuccess -> 0
               ExitFailure i -> i,
            so, [])
  mah = return $ return True

-- | Spawn process
spawn :: (ChFinalizer m,ChScanner m,ChPrinter m, ChSpawn m,Functor m) => String -> [String] -> m Int
spawn fn as = do
  ah <- mah fn
  mscanh >>= \h' -> case if ah then h' else Nothing of
    Nothing -> do
      si <- mscanL
      (i,so,hs) <- mspw fn as (Right si)
      mprint so
      mqfhs hs
      return i
    Just h -> do
      (i,so,hs) <- mspw fn as (Left h)
      mprint so
      mqfhs hs
      return i