/*
   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.
*/
package cc.drx

object Timer{
   object TimerResult{
      def apply[R](block: => R):TimerResult[R] = {
         val t0 = System.nanoTime()
         val result = block
         val t1 = System.nanoTime()
         TimerResult(result, Time(t1-t0,"ns"))
      }
   }
   case class TimerResult[R](result:R,time:Time)

   //--return the time
   def time[R](block: => R):Time = TimerResult(block).time
   def time[R](label:String)(block: => R):Time = time(label,80)(block)
   def time[R](label:String,padLabelBy:Int)(block: => R):Time = {
     print(label fit padLabelBy)
     val t = TimerResult(block).time
     println(t.format)
     t
   }

   //--stat bound of the mean
   def bound[R](n:Int)(block: => R):Bound[Time] = Stat( Iterator.fill(n){ time(block).s} ).boundMost.map{_.s}
   def bound[R](block: => R):Bound[Time] = bound(10){block}

   //--return the result with a side effect stdout
   def apply[R](block: => R): R = apply("",false){block} //unlabled by default
   def apply[R](label:String)(block: => R):R = apply(label,false){block}
   def withHeader[R](label:String)(block: => R):R = apply(label,true){block}
   def apply[R](label:String,printLabelOnStart:Boolean)(block: => R): R = {
      if(printLabelOnStart) println(f"# ${Color.Green ansi label} started:${Date.now.iso}")
      val TimerResult(result, time) = TimerResult(block)
      println(s"${Color.Green ansi label} ${Color.Blue ansi "Elapsed-time"}: ${time.format}")
      result
   }
   //--return the result and time pair
   def result[R](block: => R):TimerResult[R] = TimerResult(block)
   def pair[R](block: => R):(R,Time) = {val tr = TimerResult(block); (tr.result, tr.time)}

   //val timer = new java.util.Timer
   //def schedule[T](msDelay:Long)(body: => T):Unit = timer.schedule(new java.util.TimerTask{def run = body},msDelay)
}
object KeepTrying {
   @tailrec def apply[A](msg:String, msRetry:Long=0)(func: => A):A = Try{func} match {
      case Success(a) => a
      case Failure(e) => {
         println(s"Try again to $msg in $msRetry ms due to $e")
         //TODO use the timer task scheduler
         Thread.sleep(msRetry)
         apply(msg,msRetry)(func)
      }
   }
}