/*
   Copyright 2010 Aaron J. Radke

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
// vim: set ts=3 sw=3 et:

package cc.drx

import scala.sys.process.{Process,ProcessLogger}
import scala.concurrent.blocking

object Shell{
  //add https://stackoverflow.com/a/366532/622016
  private val Args = """[^\s"']+|"([^"]*)"|'([^']*)'""".r
   def argsOf(cmd:String):List[String] = Args.findAllMatchIn(cmd).map{ m =>
     Option(m group 1) orElse Option(m group 2) getOrElse m.matched.toString
  }.toList

  def apply(args:Iterable[String]):Shell = new Shell(args)
  def apply(cmd:String, args:String*):Shell = new Shell(argsOf(cmd) ++ args)
  def apply(args:Iterable[String],cwd:Option[File],env:Iterable[(String,String)]):Shell = new Shell(args,cwd,env)
  def apply(cmd:String,cwd:Option[File],env:Iterable[(String,String)]):Shell = new Shell(argsOf(cmd),cwd,env)
  def apply(args:Iterable[String],cwd:File):Shell = new Shell(args,Some(cwd),Nil)
  def apply(cmd:String,cwd:File):Shell = new Shell(argsOf(cmd),Some(cwd),Nil)

  case class ExitCodeFailure(code:Int,lines:List[String]) extends Throwable
}

//Shell provides a consistent cross platform wrapping to make the frustrating windows processes work more like linux
class Shell (val args:Iterable[String], val cwd:Option[File]=None, val env:Iterable[(String,String)]=List()){

  //---construction facilities
  def apply(moreArgs:String*) = this ++ moreArgs
  def ++(moreArgs:Seq[String]) = new Shell(args ++ moreArgs, cwd, env)

  private lazy val quotedArgs = args.map{arg =>
    val head = arg.take(1)
    val isQuote = head == "\"" || head == "\'"
    if(!isQuote && arg.contains(" ")) "\"" + arg + "\"" else arg
  }
  override def toString = quotedArgs.mkString(" ")

  private def fullArgs(fork:Boolean) = {
    val as = if(fork){
                  if(OS.kind == OS.Windows) {
                    if(args.nonEmpty && args.head.contains("java")) List("javaw.exe") ++ args.drop(1) //assumes java on the path
                    else List("start","/B") ++ args
                  }
                  else args.toList :+ "&"
              }
              else args

    if(OS.kind == OS.Windows && as.nonEmpty && !as.head.toLowerCase.endsWith(".exe") )
      List("cmd.exe","/Q","/C") ++ as.toList
    else as.toList
  }



  ///---launch facilities

  def fork:Process = process(fork=true).run()  //scala.sys.process.Process.run is a kind of fork that runs in the background
  //this separate cwd get switch is required since the processInternal.File does not inference correctly to cc.drx.File
  def process(fork:Boolean=false) = {
    val args = fullArgs(fork)
    // println(s"args:$args")
    if(cwd.isDefined) Process(args, cwd.get, env.toSeq:_*)
    else              Process(args, None,    env.toSeq:_*)
  }

  2017-07-30("this is just too dangerous, it's too easy to use","v0.2.15")
  def block(waitTime:Time)(implicit ec:ExecutionContext):Try[List[String]] = lines(ec).block(waitTime)

  /** run with all results sent to std out*/
  def run(implicit ec:ExecutionContext):Future[Int] = run(str => println(str))

  /** run with each line result sent to a function*/
  def run(f:String => Unit)(implicit ec:ExecutionContext):Future[Int] = Future(blocking{
    val proc:Process = process().run(ProcessLogger(f(_))) //toss assign stdin and stderr
    proc.exitValue()
  })

  def linesAs[A](f:String => A)(implicit ec:ExecutionContext):Future[List[A]] = lines(ec).map{_ map f}

  // TODO not sure about all these futures laying around since they seem to break the functional clarity
  def lines(implicit ec:ExecutionContext):Future[List[String]] = Future(blocking{
    val buffer = new scala.collection.mutable.ListBuffer[String]
    val proc:Process = process().run(ProcessLogger{x => buffer += x; ()})
    val code = proc.exitValue()
    val lines = buffer.toList
    if(code != 0) throw Shell.ExitCodeFailure(code, lines)
    lines //normally just return all the lines
  })

  def resultString(implicit ec:ExecutionContext):Future[String] = lines(ec).map{_.mkString("\n").trim}

  def exitCode(implicit ec:ExecutionContext):Future[Int] = run(_ => ())(ec) //toss lines asside; don't show
}