package models.services
import models._
import forms._
import models.services._
import org.squeryl._
import org.squeryl.PrimitiveTypeMode._

case class PartManager() extends AbstractManager{
  
  def insert(part: PartForm):Part = {
    val project = ProjectManager().getByName(part.projectName)
    val newPart = project.parts.associate(Part(part.name, part.atach))
    return newPart
  }
  
  def update(part: PartForm, id: Long):Part = {
    val project =ProjectManager().getByName(part.projectName)
    val updPart = getById(id)
    updPart.name = part.name
    updPart.projectId = project.id
    PartsListDb.parts.update(updPart)
    return updPart
  }
  
  def delete(id: Long) = {
    PartsListDb.parts.deleteWhere(p => p.id === id)
  }
  
  def partList(request: play.api.mvc.Request[play.api.mvc.AnyContent]): String = {
       var partList:String = ""
       inTransaction {
        val parts = PartsListDb.parts.where(p => p.name like request.getQueryString("q").get + "%")
        for(part <- parts) {
          partList = partList.concat(part.name)
          partList = partList.concat("\n")
         }
        }
       return partList
  }
  
  def getById(id: Long):Part = {
    return PartsListDb.parts.where(p => p.id === id).head
  }
  
  def getByName(name: String):Part ={
    return PartsListDb.parts.where(p => p.name === name).head
  }
  
  def getByLikeName(key: String) ={
    PartsListDb.parts.where(p => p.name like key + "%" )
  }
}