package controllers

import play.api._
import play.api.i18n._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import forms._
import models._
import models.services._
import beans._
import services._
import org.squeryl._
import org.squeryl.PrimitiveTypeMode._
import scala.collection.mutable.ArrayBuffer

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

   val partRegistForm = Form(
       mapping(
           "name" -> nonEmptyText,
           "atach" -> mapping(
               "grpName" -> text
             )(AtachForm.apply)(AtachForm.unapply),
           "projectName" -> nonEmptyText
        )(PartForm.apply)(PartForm.unapply)
    )

	def create = Action { implicit request =>
	  Ok(views.html.createPartForm(partRegistForm))
	}

	def partRegistration() = Action(parse.multipartFormData) { implicit request =>
	  partRegistForm.bindFromRequest.fold(
	      formWithErrors => BadRequest(views.html.createPartForm(formWithErrors)),
//	      formWithErrors => BadRequest(views.html.error(formWithErrors)),
	      part => {
	        inTransaction {
	          val newPart = PartManager().insert(part)
              request.body.file("atach").map { atach =>
              	AtachManager().uploadAtach(atach, newPart.atach.grpName, newPart.id, 0, 0)
	    	    }
	    	  Home.flashing("success" -> "Part %s has been created".format(part.name))
	        }  
	      }
	  )
	}

	def update(id:Long) = Action { implicit request =>
	  inTransaction {
	    val part = PartManager().getById(id)
	    val partForm = PartForm(part.name, null, part.project.assign(part.project.head).name)
		Ok(views.html.updatePartForm(partRegistForm.fill(partForm), id, part))
	  }
	}

	def partModification(id:Long) = Action(parse.multipartFormData) { implicit request =>
	  partRegistForm.bindFromRequest.fold(
	      formWithErrors => BadRequest(views.html.updatePartForm(formWithErrors, id , null)),
	      part => {
	        inTransaction {
	          val updPart = PartManager().update(part, id)
	    	   request.body.file("atach").map { atach =>
	    	     AtachManager().uploadAtach(atach, part.atach.grpName, updPart.id, 0, 0)
	    	    }
	    	  Home.flashing("success" -> "Part %s has been created".format(part.name))
	        }  
	      }
	  )
	}

	def partDelete(id:Long) = Action {
	  inTransaction {
	    PartsListDb.parts.deleteWhere(p => p.id === id)
    	Home.flashing("success" -> "Part %s has been created".format(id))
	  }
	}
	
	def list(page:Int, key:String) = Action { implicit request =>
	  inTransaction {
		  val row = Integer.decode(Messages("list.row"))
		  val buff = PartsListDb.parts.where(p => p.name like key + "%")
		  Ok(views.html.partsmastershow(buff.page(page*row, row), buff.size, key, page))
	  }
	}	

}