package controllers.services
import models._
import beans._
import scala.collection.mutable.ArrayBuffer
case class PartRecursion(){
   
  def down(parentPart: Part, parentQuantity: Long, opt: Int, key: String):ArrayBuffer[PartsListShowBean] = {
    val partBuffer = ArrayBuffer[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 += PartsListShowBean(parentPart.name, child, quantity, pr.relationKey, quantity * child.price)
          } else {
            if(pr.relationKey.equals(key)) {
              partBuffer += PartsListShowBean(parentPart.name, child, quantity, pr.relationKey, quantity * child.price)
             }
           }
	     }
//	    if(opt==1 || opt==2 && !child.name.startsWith("Part") || opt==3) {
	    if(opt==1 || opt==2 && child.price.==(0) || opt==3) {
	      val partBuffers = PartRecursion().down(child, quantity, opt, key)
	      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) {
	       val pr = parent.partRelation(childPart.id)
	       partBuffer += PartsListBean(childPart.name, parent.name, pr.quantity, pr.relationKey)
	      }
		  if(opt != 1) {
		    for(returnPartBuffer <- PartRecursion().up(parent, opt)) {
		      partBuffer += returnPartBuffer
		    }
		  }
		}
	  }
	 return partBuffer
  }

}