package models.services
import models._
import models.services.impl._
import forms._
import models.services._
import org.squeryl._
import org.squeryl.PrimitiveTypeMode._
import com.google.inject._
import modules._

case class PartManager() extends AbstractManager{
  val inject = Guice.createInjector(new ServiceModules)
  val projectManager = inject.getInstance(classOf[ProjectManager])

  
  def insert(part: PartForm):Part = {
    val project = projectManager.getByName(part.projectName)
    val newPart = project.parts.associate(Part(part.name, part.atach, part.price))
    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
    updPart.price = part.price
    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 = {
    PartsListDb.parts.where(p => p.id === id).head
  }
  
  def getByName(name: String):Query[Part] ={
      PartsListDb.parts.where(p => p.name === name)
  }
  
  def getByLikeName(key: String) ={
    PartsListDb.parts.where(p => p.name like key + "%" )
  }
}