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

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

}