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._
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 partsBuffer = ArrayBuffer[PartsListShowBean]()
	    inTransaction {
		  for (parentPart <- PartManager().getByLikeName(key)) {
		    for(returnPartBuffer <- PartRecursion().down(parentPart, 1, opt)) {
		      partsBuffer += returnPartBuffer
		    }
		  }
	    }
		var totalCost:Long =0
		for(partBuffer <- partsBuffer) {
		  totalCost += partBuffer.cost
		}
		val row = Integer.decode(Messages("list.row"))
		Ok(views.html.partslistshow(partsBuffer.drop(page*row).take(row), opt, page, partsBuffer.size, key, totalCost))
	}

	def upIndex(opt:Int, page:Int, key:String) = Action { implicit request =>
	  var partBuffer = ArrayBuffer[PartsListBean]()
	  inTransaction {
		  for (childPart <- PartManager().getByLikeName(key)) {
		    for(returnPartBuffer <- PartRecursion().up(childPart, opt)) {
		      partBuffer += returnPartBuffer
		    }
		  }
	   }
	   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 = PartRelationManager().insert(data, null, 0)
		    if( message == null) {
			  Home.flashing("success" -> "Relation %s has been created".format(data.parent))
		    } else {
	         Ok(views.html.createRelationForm(relationForm.fill(data), message))
		    }
		   }
	  }
     )
	}
	
	def relationUpdate(childName:String) = Action { implicit request =>
	  relationForm.bindFromRequest.fold(
		   formWithErrors => BadRequest(views.html.updateRelationForm(formWithErrors, null, "")),
	   data => {
	     inTransaction {
	       val message = PartRelationManager().update(data, childName)
	       if(message == null) {
	         Home.flashing("success" -> "Relation %s has been created".format(data.parent))
	        } else {
	          Ok(views.html.updateRelationForm(relationForm.fill(data), childName, 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)
	  }
	}
	
}