package controllers.services
import models._
import beans._
import scala.collection.immutable.Seq
case class PartRecursion(){
   
  def down(parentPart: Part, parentQuantity: Long, opt: Int, key: String):Seq[PartsListShowBean] = {
    var partBuffer = Seq[PartsListShowBean]()
    for(child <-parentPart.parts) {
      val pr = parentPart.partRelation(child.id)
      if(pr.delDcId==0) {
        var quantity:Long = 0
        if(opt==2) {
        	quantity = parentQuantity * pr.quantity
         } else {
        	quantity = pr.quantity           
          }
        if(opt!=3 || opt==3 && child.name.startsWith("Unit")) {
          if(key.isEmpty()) {
        		partBuffer = partBuffer.:+(PartsListShowBean(parentPart.name, child, quantity, pr.relationKey, quantity * child.price))
          } else {
            if(pr.relationKey.equals(key)) {
              partBuffer = partBuffer.:+(PartsListShowBean(parentPart.name, child, quantity, pr.relationKey, quantity * child.price))
             }
           }
	     }
	    if(opt==1 || opt==2 && child.price.==(0) || opt==3) {
	      val partBuffers = PartRecursion().down(child, quantity, opt, key)
	      for (returnPartBuffer <- partBuffers) {
	        partBuffer = partBuffer.:+(returnPartBuffer)
	        }
	    }
	   }
    }
    return partBuffer
  }

  def up(childPart: Part, opt: Int): Seq[PartsListBean] = {
    var partBuffer = Seq[PartsListBean]()
    if(childPart.parentParts.size == 0 && opt == 2) {
	   partBuffer = partBuffer.:+(PartsListBean("", childPart.name, 0, ""))
	 }
	 for(parent <- childPart.parentParts) {
	   if(parent.partRelation(childPart.id).delDcId == 0 ) {
	     if(opt != 2) {
	       val pr = parent.partRelation(childPart.id)
	       partBuffer = partBuffer.:+(PartsListBean(childPart.name, parent.name, pr.quantity, pr.relationKey))
	      }
		  if(opt != 1) {
		    for(returnPartBuffer <- PartRecursion().up(parent, opt)) {
		      partBuffer = partBuffer.:+(returnPartBuffer)
		    }
		  }
		}
	  }
	 return partBuffer
  }

}