package controllers
import play.api._
import play.api.i18n._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import models.services._
import forms._
import org.squeryl._
import org.squeryl.PrimitiveTypeMode._
import org.squeryl.annotations.Column

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 {
            DesignChangeManager().insert(designChange)
          }
   	    	  Home.flashing("success" -> "Design Change %s has been created".format(designChange.dcNo))       
        }
     )
  }
  
  def designChangeCoverModify(id: Long) = Action { implicit request =>
    inTransaction {
      val designChange = DesignChangeManager().getById(id)
      val designChangeForm = DesignChangeForm(designChange.dcNo, designChange.dcDescription)
      val designChangeBuffer = DesignChangeManager().getDesinChangeInformation(designChange)
      Ok(views.html.updateDesignChangeForm(designChangeRegistForm.fill(designChangeForm), id, designChangeBuffer, designChange.addPartRelation))
    }
  }

  def designChangeCoverModification(id: Long) = Action{ implicit request =>
    designChangeRegistForm.bindFromRequest.fold(
        formWithErrors => BadRequest(views.html.updateDesignChangeForm(formWithErrors, id, null, null)),
        designChange => {
          inTransaction {
            DesignChangeManager().update(id, designChange)
          }
      	  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 = DesignChangeManager().list(key)
      Ok(views.html.designchangelist(buff.page(page*row, row), buff.size, key, page))
    }
  }
  
  def designChangeCancel(id: Long) = Action { 
           inTransaction {
             DesignChangeManager().designChangeCancel(id)
             Redirect(routes.DesignChangeController.designChangeCoverModify(id))
           }
  }
  
}