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 forms._
import org.squeryl._
import org.squeryl.PrimitiveTypeMode._

object DesignChangeController extends Controller{
  
   val Home = Redirect(routes.DesignChangeController.list(0,""))

   val designChangeRegistForm = Form(
      mapping(
          "dcNo" -> nonEmptyText,
          "dcDescription" -> nonEmptyText
       )(DesignChangeForm.apply)(DesignChangeForm.unapply)
  )
  
  def create = Action { implicit request =>
    Ok(views.html.createDesignChangeForm(designChangeRegistForm))
  }
  
  def designChangeCoverRegistration() = Action { implicit request =>
    designChangeRegistForm.bindFromRequest.fold(
        formWithErrors => BadRequest(views.html.createDesignChangeForm(formWithErrors)),
        designChange => {
          inTransaction {
            PartsListDb.designChanges.insert(DesignChange(designChange.dcNo, designChange.dcDescription))
          }
   	    	  Home.flashing("success" -> "Design Change %s has been created".format(designChange.dcNo))       
        }
     )
  }
  
  def designChangeCoverModify(id: Long) = Action { implicit request =>
    inTransaction {
      val designChange = getDesignChange(id)
      val designChangeForm = DesignChangeForm(designChange.dcNo, designChange.dcDescription)
      Ok(views.html.updateDesignChangeForm(designChangeRegistForm.fill(designChangeForm), id, designChange.delPartRelation, designChange.addPartRelation))
    }
  }

  def designChangeCoverModification(id: Long) = Action{ implicit request =>
    designChangeRegistForm.bindFromRequest.fold(
        formWithErrors => BadRequest(views.html.updateDesignChangeForm(formWithErrors, id, null, null)),
        designChange => {
          inTransaction {
            val updDesignChange = getDesignChange(id)
            updDesignChange.dcNo = designChange.dcNo
            updDesignChange.dcDescription = designChange.dcDescription
            PartsListDb.designChanges.update(updDesignChange)
          }
      	  Home.flashing("success" -> "Design Change %s has been created".format(designChange.dcNo))       
        }
    )
  }
  
  def list(page: Int, key: String) = Action { implicit request =>
    inTransaction {
      val row = Integer.decode(Messages("list.row"))
      val buff = PartsListDb.designChanges.where(dc => dc.dcNo like key + "%")
      Ok(views.html.designchangelist(buff.page(page*row, row), buff.size, key, page))
    }
  }
  
  def getDesignChange(id: Long):DesignChange = {
    PartsListDb.designChanges.where(dc => dc.id === id).head
  }
}