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

case class 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)
      PartsListDb.projects.update(updProject)
     }
  }
  
  def deleteMember(projectId: Long, memberId: Long) = {
    val project = PartsListDb.projects.where(pr => pr.id === projectId).head
    val member = PartsListDb.users.where(u => u.id === memberId).head
    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
  }

}