package controllers

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

object PartsListController extends Controller{
  
   val Home = Redirect(routes.PartsListController.index(0,0,""))
   val Home2 = Redirect(routes.PartsListController.relationRegistration())
   val relationForm = Form(
       mapping(
           "parent" -> nonEmptyText,
           "child" -> nonEmptyText,
           "quantity" -> longNumber
        )(PartsListBean.apply)(PartsListBean.unapply)
    )
    
	def index(opt:Int, page:Int, key:String) = Action { implicit request =>
		var partBuffer = ArrayBuffer[PartsListBean]()
	    inTransaction {
		  for (parentPart <- PartManager().getByLikeName(key)) {
		    PartRecursion().down(parentPart, partBuffer, opt)
		  }
	    }
	  val row = Integer.decode(Messages("list.row"))
	  Ok(views.html.partslistshow(partBuffer.drop(page*row).take(row), opt, page, partBuffer.size, key))
	}

	def upIndex(opt:Int, page:Int, key:String) = Action { implicit request =>
	  var partBuffer = ArrayBuffer[PartsListBean]()
	  inTransaction {
		  for (childPart <- PartManager().getByLikeName(key)) {
		    PartRecursion().up(childPart, partBuffer, opt)
		  }
	   }
	   val row = Integer.decode(Messages("list.row"))
	   Ok(views.html.uppartslistshow(partBuffer.drop(page*row).take(row), opt, page, partBuffer.size, key))
	}

	def createRelation(parent:String) = Action {implicit request =>
	  Ok(views.html.createRelationForm(relationForm.fill(new PartsListBean(parent, "", 0)),""))
	}
	
	def updateRelation(parentNo:String, childNo:String) = Action { implicit request =>
	  inTransaction {
		  Ok(views.html.updateRelationForm(relationForm.fill(generatePartsListBean(parentNo, childNo)), childNo, ""))
	  }
	}
	
	def relationRegistration() = Action { implicit request =>
	  relationForm.bindFromRequest.fold(
	      formWithErrors => BadRequest(views.html.createRelationForm(formWithErrors, "")),
	   data => {
		   inTransaction {
		    val message = Check().loopCheck(data)
		    if(message == null) {
		      PartRelationManager().insert(data)
			  Home.flashing("success" -> "Relation %s has been created".format(data.parent))
		    } else {
	         Ok(views.html.createRelationForm(relationForm.fill(data), Messages(message)))
		    }
		   }
	  }
     )
	}
	
	def relationUpdate(childName:String) = Action { implicit request =>
	  relationForm.bindFromRequest.fold(
		   formWithErrors => BadRequest(views.html.updateRelationForm(formWithErrors, null, "")),
	   data => {
	     inTransaction {
	       val message = Check().loopCheck(data)
	       if(message == null) {
	         PartRelationManager().update(data, childName)
	         Home.flashing("success" -> "Relation %s has been created".format(data.parent))
	        } else {
	          Ok(views.html.updateRelationForm(relationForm.fill(data), childName, Messages(message)))
	        }
	      }
	    }
	  )
	}
	
	def relationDelete(parentName:String, childName:String) = Action {
	  inTransaction {
	    val data = PartsListBean(parentName, childName, 0)
	    PartRelationManager().delete(data, childName)
	    Home.flashing("success" -> "Relation %s has been deleted".format(parentName + "/" + childName))
	  }
	}
	
	def generatePartsListBean(parentNo:String, childNo:String):PartsListBean = {
	  if(childNo.isEmpty()) {
	      PartsListBean(parentNo, childNo, 0)
	  } else {
		  PartsListBean(parentNo, childNo, PartManager().getByName(parentNo).partRelation(PartManager().getByName(childNo).id).quantity)
	  }
	}

}