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)
    )
    
    val designChangeRegistForm = Form(
        mapping(
            "partsListBeanBefore" -> mapping(
                "parent" -> nonEmptyText,
                "child" -> text,
                "quantity" -> longNumber
                )(PartsListBean.apply)(PartsListBean.unapply),
              "partsListBeanAfter" -> mapping(
                  "parent" -> nonEmptyText,
                  "child" -> text,
                  "quantity" -> longNumber
                  )(PartsListBean.apply)(PartsListBean.unapply),
            "dcno" -> nonEmptyText
         )(DesignChangeRelationForm.apply)(DesignChangeRelationForm.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 designChangeForm(parentName:String, childName:String) = Action { implicit request =>
	      	inTransaction {
	      	  val designChangeRelationForm = DesignChangeRelationForm(generatePartsListBean(parentName, childName), generatePartsListBean(parentName, childName), "")
	      		Ok(views.html.designChangeRelationForm(designChangeRegistForm.fill(designChangeRelationForm), ""))
	      	}
	}
	
	def designChange() = Action { implicit request =>
	  designChangeRegistForm.bindFromRequest.fold(
	      formWithErrors => BadRequest(views.html.designChangeRelationForm(formWithErrors, "")),
	      data => {
	    	  inTransaction {
	    	    val message = Check().loopCheckDc(data)
	    	    if(message == null) {
	    	      DesignChangeManager().designChange(data)
	    	      Home.flashing("success" -> "Relation %s has been changed".format(data.partsListBeanBefore.parent + "/" + data.partsListBeanBefore.child))
	    	    } else {
	    	      Ok(views.html.designChangeRelationForm(designChangeRegistForm.fill(data), Messages(message)))
	    	    }
	    	  }
	      }
	  )
	}
		
	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)
	  }
	}

}