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.PrimitiveTypeMode._
import java.io.FileInputStream

case class AtachManager() {
  def uploadAtach(atach:FilePart[TemporaryFile], grpName:String, partId:Long, notifyId:Long, replyId:Long) = {
      val filename = atach.filename
      val contentType = atach.contentType
      var folder = Messages("atach.folder")
      if(!folder.endsWith("/")) {folder = folder.concat("/")}
      val url = folder + filename
      atach.ref.moveTo(new File(url), true)
      PartsListDb.atachs.insert(Atach(contentType.get, filename, grpName, partId, notifyId, replyId))
  }
  
  def showAtach(id: Long):Array[Byte] = {
    val atach = getById(id)
    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(p => p.id === id).head
  }
  
  def delete(id: Long) = {
    PartsListDb.atachs.deleteWhere(a => a.id === id)
  }
}