/*
   vim: set ts=3 sw=3 et:
   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.p5

//import scala.collection.JavaConverters._

//import scala.language.implicitConversions
//import scala.annotation.tailrec

import processing.core._
import processing.core.PConstants._
import processing.core.PApplet._

import scala.concurrent.ExecutionContext.Implicits.global

import cc.drx._
import cc.drx.p5._
import cc.drx.p5.P5._
import cc.drx.p5.Draw._
import cc.drx.Style._
import cc.drx.Implicits._

object KsonDraw extends P5App
class KsonDraw extends P5{
   //Option(args) foreach println
   //implicit
   val ctx = this
   override val renderClass = JAVA2D// P2D // OPENGL // P3D // OPENGL // JAVA2D

   val kson = Kson.Watched.empty
   def interpolate(v:String):String = kson.kson.interpolate(v)

   override def setup = {
      super.setup
      println("Working directory:" + File(".").canon)
      for(as <- Option(args); a <- as.headOption) kson.update(File(a)) //check if args is defined if so then loop through the first one
      // println(kson.tree)
   }

   val defaultStyle = Fill(Black) ~ Weight(1)


   //TODO make this look more like the cpp gen code
   //TODO special variables, $i:sibling number, $mouse: mouse vec
   def drawTree(tree:MTree[KsonLine]):Unit = {
      val l = tree.value

      def localGet[A](k:String)(implicit parser:Parsable[A]):Option[A] = //TODO string interpolation of $values for more capable and string values
         for(v <- l.kvs.toMap get k; s = interpolate(l.interpolate(v))) yield Parse(s)

      val kvs = (l.scope.flatMap{_.kvs} ::: l.kvs).toMap //merge properties from parent scopes

      def get[A](k:String)(implicit parser:Parsable[A]):Option[A] = //TODO string interpolation of $values for more capable and string values
         for(v <- kvs get k; s = interpolate(l.interpolate(v))) yield Parse.apply(s)

      def split[A](k:String,sep:String="""\s+""")(implicit parser:Parsable[A]):Option[Vector[A]] = //TODO string interpolation of $values for more capable and string values
         for(v <- kvs get k; s = interpolate(l.interpolate(v))) yield Parse.split(s,sep)

      val style:Style = List[Option[Style.Property]](
            get[Color]("f") map Fill.apply,
            get[Color]("s") map Stroke.apply,
            get[Double]("k") map {k=>ScaleProperty(Vec(k,k))},
            get[Double]("lw") map Weight.apply
         ).foldLeft(Style()){
            case (s,Some(p)) => s ~ p
            case (s,None)    => s
         }
      val s = if(style.isEmpty) defaultStyle else style

      for(v <- localGet[Color]("bg")) background(v)
      for(v <- localGet[Angle]("rotate")) rotate(v.rad)
      for(v <- localGet[Vec]("scale")) scale(v.x, v.y)
      for(v <- localGet[Vec]("translate")) translate(v.x, v.y)

      //--shapes
      for(c <- get[Vec]("c")){
         val label = get[String]("l")
         if(label.isDefined){
            g ! Text(label.get, Vec.zero) ~ Translate(c) ~ s ~ Center ~ Midline
         }
         else{
            val r = get[Double]("r") getOrElse 1.0
            g ! Circ(c, r) ~ s
         }
      }
      for(cs <- split[Vec]("cs","""\s*,\s*""")){
         val r = get[Double]("r") getOrElse 1.0
         for(c <- cs) g ! Circ(c, r) ~ s
      }
      for(cs <- split[Vec]("poly","""\s*,\s*""")){
         g ! Poly(cs) ~ s
      }

      //--draw shapes
      val loop = for(loop <- localGet[Time]("loop") ) yield loop
      val kids = tree.kids.toVector
      if(loop.isDefined)
         loop foreach {dt =>
            //val dt = loop.get / tree.kids.size
            val N = kids.size
            val i = ((Date.ms % dt.ms)*N/dt.ms).toInt// (((Date.ms/dt.ms*pi).sin + 1)/2*N % N).toInt
            kids lift i foreach drawTree //select child to use for the loop....
         }
      else kids foreach drawTree
   }
   override def draw = {
      background(White)
      pushMatrix
         translate(width/2, height/2)
         noFill
         noStroke
         for(tree <- kson.kson.interpolated.tree.kids) drawTree(tree)
      popMatrix

      //g ! mouse ~ 2 ~ Fill(Grey)
      //g ! File(".").canon.path ~ Vec(width,10) ~ Fill(Grey) ~ Right ~ Top
      g ! s"${frameRate.round.toInt} fps" ~ width.x ~ Fill(Grey) ~ Right ~ Top
   }
}