package models.services
import models._
import play.api.i18n._
import play.api.mvc.MultipartFormData.FilePart
import play.api.libs.Files.TemporaryFile
import java.io.File
import org.squeryl._
import org.squeryl.dsl._
import org.squeryl.PrimitiveTypeMode._
import java.io.FileInputStream
import java.io.BufferedInputStream

case class AtachManager(){
  def uploadAtach(atach:Any, contentType:String, grpName:String, partId:Long, notifyId:Long, replyId:Long) = {
    var fis:FileInputStream = null
    var fLength:Int = 0
    var fileName:String = null
    if(atach.isInstanceOf[FilePart[TemporaryFile]]) {
      fileName = atach.asInstanceOf[FilePart[TemporaryFile]].filename
      val file = atach.asInstanceOf[FilePart[TemporaryFile]].ref.file
      fis = new FileInputStream(file)
      fLength = file.length().toInt
    }
    if(atach.isInstanceOf[File]) {
      fileName = atach.asInstanceOf[File].getName()
      fis = new FileInputStream(atach.asInstanceOf[File])
      fLength = atach.asInstanceOf[File].length().toInt
    }
      val bis = new BufferedInputStream(fis)
      val  byteBuffer = new Array[Byte](fLength)
      bis.read(byteBuffer)
      bis.close()
      fis.close()
      //実ファイルで実装するなら以下５行で実装
/*      var folder = Messages("atach.folder")
      if(!folder.endsWith("/")) {folder = folder.concat("/")}
      val url = folder + filename  
      val file = new File(url)
      atach.ref.moveTo(new File(url), true)
*/    
      val newAtach = Atach(byteBuffer, contentType, fileName, grpName, partId, notifyId, replyId)
      if(partId != 0) {
        associateAtach(PartManager(), partId, newAtach)
       }
      if(notifyId != 0) {
        associateAtach(NotifyManager(), notifyId, newAtach)
      }
      if(replyId != 0) {
        associateAtach(ReplyManager(), replyId, newAtach)
      }
  }
 
  def showAtach(id: Long):Array[Byte] = {
    val atach = getById(id)
    return atach.lob
    // 実ファイルで実装するなら以下５行
/*    val file = new File(Messages("atach.folder") + "/" + atach.fileName)
    val data = new Array[Byte](file.length().asInstanceOf[Int])
    val io = new FileInputStream(file)
    io.read(data)
    io.close
    return data*/
  }
  
  def getById(id: Long):Atach = {
    PartsListDb.atachs.where(a => a.id === id).head
  }
  
  def delete(id: Long) = {
    PartsListDb.atachs.deleteWhere(a => a.id === id)
  }
  
  def associateAtach(manager: AbstractManager, id: Long, atach:Atach) = {
    manager.getById(id).atachs.associate(atach)
  }
}