package models.services
import beans._
import models._
import controllers.services._
import org.squeryl._
import org.squeryl.PrimitiveTypeMode._
case class PartRelationManager() {
  def insert(data:PartsListBean, dc:DesignChange, dcSeq: Long):String = {
    if(Check().loopCheck(data)) {
      val pr = PartManager().getByName(data.parent).parts.associate(PartManager().getByName(data.child))
      // insertの後、attributeの更新
      updatePr(pr, data.quantity, dcSeq, null, dc)
      return null
    } else {
      return "form.error1"
    }
  }
  
  def update(data:PartsListBean, childName:String):String = {
    if(data.child == childName) {
      if(Check().loopCheck(data)) {
        //PartRelation データ更新処理
        val pr = PartManager().getByName(data.parent).parts.assign(PartManager().getByName(data.child))
        updatePr(pr, data.quantity, 0, null, null)
        return null
      } else {
       return "form.error1"
       }
    } else {
      //PartRelation キー情報（ChildId）の更新なので削除／登録処理
      delete(data, childName)
      insert(data, null, 0)
     }
  }
  
  def updatePr(pr: PartRelation, quantity: Long, dcSeq: Long, delDc: DesignChange, addDc: DesignChange) = {
    if(delDc != null) {
      delDc.delPartRelation.assign(pr)
    }
    if(addDc != null) {
      addDc.addPartRelation.associate(pr)
    }
    pr.quantity = quantity
    pr.dcSeq = dcSeq
    PartsListDb.partRelations.update(pr)
    if(delDc != null) {
      delDc.delPartRelation.assign(pr)
    }
    if(addDc != null) {
      addDc.addPartRelation.associate(pr)
    }
  }
  
  def delete(data: PartsListBean, childName: String) = {
       PartManager().getByName(data.parent).parts.dissociate(PartManager().getByName(childName))
  }
  
}