package controllers

import mvc.AuthAction
import play.api._
import play.api.i18n._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import models._
import models.services._
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 = AuthAction {
    Action { implicit request =>
      if(request == null) {
         Ok(views.html.errors.errorNotAuthentication())
      } else {
        Ok(views.html.createUserForm(userForm))
       }
    }
  }
  
  def userRegistration() = Action { implicit request =>
    userForm.bindFromRequest.fold(
        formWithErrors => BadRequest(views.html.createUserForm(formWithErrors)),
        user => {
          inTransaction {
            UserManager().insert(user)
            Home.flashing("success" -> "User %s has been created".format(user.name))
          }
        }
     )
  }
  
  def updateUser(id: Long) = AuthAction {
    Action{ implicit request =>
      if(request == null) {
         Ok(views.html.errors.errorNotAuthentication())
      } else {
        inTransaction {
          val user = UserManager().getById(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 {
            UserManager().update(user, id)
            Home.flashing("success" -> "User %s has been updated".format(user.name))
          }
        }
     )
  }
  
  def list(page: Int, key: String) = AuthAction {
    Action{ implicit request =>
      if(request == null) {
         Ok(views.html.errors.errorNotAuthentication())
      } else {
        inTransaction {
          val row = Integer.decode(Messages("list.row"))
          val buff = UserManager().list(key)
          Ok(views.html.userlist(buff.page(page*row, row), buff.size, key, page))
          }
        }
    }
  }
}
    