package controllers
import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import forms._
import models._
import utils._
import org.squeryl._
import org.squeryl.PrimitiveTypeMode._
object ReplyController extends Controller{
  val replyRegistForm = Form(
      mapping(
          "message" -> nonEmptyText,
          "users" -> mapping (
              "name" -> nonEmptyText
            )(UserForm.apply)(UserForm.unapply),
            "atach" -> mapping {
                "grpName" -> text
              }(AtachForm.apply)(AtachForm.unapply)
        )(ReplyForm.apply)(ReplyForm.unapply)
   )
   
  def createReply(notifyId: Long, replyId: Long, notifyType: Long, replyType: Long, partId: Long, state: Long) = Action { implicit request =>
    Ok(views.html.createReplyForm(replyRegistForm, notifyId, replyId, replyType, partId, notifyType, state))
  }
  
  def replyRegistration(notifyId: Long, replyId: Long, partId: Long, notifyType: Long, state: Long) = Action(parse.multipartFormData) { implicit request =>
    replyRegistForm.bindFromRequest.fold(
        formWithErrors => BadRequest(views.html.createReplyForm(formWithErrors, notifyId, replyId, 0, partId, notifyType, state)),
        reply => {
          inTransaction {
            val replyUser = PartsListDb.users.where(u => u.name like reply.users.name + "%").head
            val newReply = PartsListDb.replies.insert(Reply(reply.message, replyUser.id, notifyId, replyId, reply.atach))
            val uploadAtach = UploadAtach()
            request.body.file("atach").map { atach =>
              	uploadAtach.uploadAtach(atach, newReply.atach.grpName, 0, 0, newReply.id)
              }
            var notify: Notify = null
            if(notifyId!=0) {
            	// 通知直下のreplyの場合、notifyより対象Partを割り出し、プロジェクトユーザー抽出。メイル通知。
            	notify = PartsListDb.notifies.where(n => n.id === notifyId).head
            } else {
              // reply配下のreplyの場合、再帰処理によりnotify抽出後、対象Partを割り出し、プロジェクトユーザー抽出。メイル通知。
              val targetReply = PartsListDb.replies.where(tr => tr.id === replyId).head
            	val topReply = upRecursion(targetReply)
            	notify = PartsListDb.notifies.where(n => n.id === topReply.notifyId).head              
              }	
            val targetPart = notify.part.assign(notify.part.head)
            val users = targetPart.project.assign(targetPart.project.head).users
            val sendMail = SendMail(2, replyUser.email, targetPart.id, notifyType, state)
            for(user <- users) {
               sendMail.sendMail(user.email)
              }
           }
          Ok(views.html.issueresult(2))
         }
     )
  }
  
  def showReply(id: Long, partId: Long, notifyType: Long, replyType: Long, state: Long) = Action { implicit request =>
    inTransaction {
      val reply = PartsListDb.replies.where(r => r.id === id).head
      val replyForm = ReplyForm(reply.message, UserForm(reply.user.assign(reply.user.head).name), null)
      Ok(views.html.showReplyForm(replyRegistForm.fill(replyForm), id, partId, notifyType, replyType, state, reply))
    }
  }
  
  def upRecursion(reply: Reply):Reply = {
    if(reply.parentReply.size == 0) {
      return reply
    } else {
      println("Messages " + reply.message)
      upRecursion(reply.parentReply.head)
    }
  }
  
  def appendAtach(id: Long, partId: Long, notifyType: Long, replyType: Long, state: Long) = Action(parse.multipartFormData) { implicit request =>
    replyRegistForm.bindFromRequest.fold(
        formWithErrors => BadRequest(views.html.showReplyForm(formWithErrors, id, partId, notifyType, replyType, state, null)),
//        formWithErrors => BadRequest(views.html.error(formWithErrors)),
        reply => {
          inTransaction {
            val uploadAtach = UploadAtach()
            request.body.file("atach").map { atach =>
              	uploadAtach.uploadAtach(atach, reply.atach.grpName, 0, 0, id)
              }
            Redirect(routes.ReplyController.showReply(id, partId, notifyType, replyType, state))
            }
          }
     )
  }
}