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

case class ProjectManagerImpl() extends ProjectManager{
  
  def insert(project: ProjectForm):Project = {
    PartsListDb.projects.insert(Project(project.name))
  }
  
  def update(project: ProjectForm, id: Long) = {
    val updProject = getById(id)
    updProject.name = project.name
    if(!project.users.name.isEmpty()) {
      val user = UserManager().getByName(project.users.name)
      updProject.users.associate(user)
     }
  }
  
  def deleteMember(projectId: Long, memberId: Long) = {
    val project = getById(projectId)
    val member = UserManager().getById(memberId)
    project.users.dissociate(member)
  }
  
  def list(key: String): org.squeryl.Query[Project] = {
    PartsListDb.projects.where(pr => pr.name like key + "%")
  }
  
  def getByName(name: String):Project = {
    PartsListDb.projects.where(p => p.name === name).head
  }
  
  def getById(id: Long) = {
    PartsListDb.projects.where(pr => pr.id === id).head
  }
  
  def getProjectList(request: play.api.mvc.Request[play.api.mvc.AnyContent]): String = {
       var projectList:String=""
      inTransaction {
	    val projects =PartsListDb.projects.where(p => p.name like request.getQueryString("q").get + "%")
	    for(project <- projects) {
	      projectList = projectList.concat(project.name)
	      projectList = projectList.concat("\n")
	    }
	  }
    return projectList
  }

}