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