package controllers
import play.api._
import play.api.i18n._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import models._
import org.squeryl._
import org.squeryl.PrimitiveTypeMode._
object UserController extends Controller{
  val Home = Redirect(routes.UserController.list(0, ""))
  val userForm = Form(
      mapping(
          "name" -> nonEmptyText,
          "email" -> nonEmptyText
       )(User.apply)(User.unapply)
  )
  
  def createUser = Action { implicit request =>
    Ok(views.html.createUserForm(userForm))
  }
  
  def userRegistration() = Action { implicit request =>
    userForm.bindFromRequest.fold(
        formWithErrors => BadRequest(views.html.createUserForm(formWithErrors)),
        user => {
          inTransaction {
            PartsListDb.users.insert(User(user.name, user.email))
            Home.flashing("success" -> "User %s has been created".format(user.name))
          }
        }
     )
  }
  
  def updateUser(id: Long) = Action{ implicit request =>
    inTransaction {
      val user = getUser(id)
      val updUser = User(user.name, user.email)
      Ok(views.html.updateUserForm(userForm.fill(updUser), id))
    }
  }
  
  def userModification(id: Long) = Action{ implicit request =>
    userForm.bindFromRequest.fold(
        formWithErrors => BadRequest(views.html.updateUserForm(formWithErrors, id)),
        user => {
          inTransaction {
            val updUser = getUser(id)
            updUser.name = user.name
            updUser.email = user.email
            PartsListDb.users.update(updUser)
            Home.flashing("success" -> "User %s has been updated".format(user.name))
          }
        }
     )
  }
  
  def list(page: Int, key: String) = Action{ implicit reauest =>
    inTransaction {
      val row = Integer.decode(Messages("list.row"))
      val buff = PartsListDb.users.where(u => u.name like key + "%")
      Ok(views.html.userlist(buff.page(page*row, row), buff.size, key, page))
    }
  }
  
  def getUser(id: Long):User ={
    PartsListDb.users.where(u => u.id === id ).head
  }
}