package controllers

import play.api._
import play.api.i18n._
import play.api.mvc._
import java.io.File
import java.io.FileInputStream
import models.PartsListDb
import models.Atach
import org.squeryl._
import org.squeryl.PrimitiveTypeMode._

object Application extends Controller {
  
  def index = Action { implicit request =>
    Ok(views.html.index("Your new application is not ready."))
  }
  
  def picture = Action {
    Ok(views.html.uploadTestForm())
  }
  
  def upload = Action(parse.multipartFormData) { request =>
      inTransaction {
    request.body.file("picture").map { picture =>
      val filename = picture.filename
      val contentType = picture.contentType
      var atach = Messages("atach.folder")
      if(!atach.endsWith("/")) {atach = atach.concat("/")}
      val url = atach + filename
      picture.ref.moveTo(new File(url), true)
      PartsListDb.atachs.insert(Atach(contentType.get, filename, "AAA", 1))
      
      Ok("File upload -- " + filename + " -- "+ contentType.get)
    }.getOrElse{
      Redirect(routes.Application.index).flashing(
          "error" -> "Missing file"
       )
    }
     }
  }
  
  def show = Action {
    val file = new File("/home/uyaji/git/Relation/PartsList/attach/picture.jpg")
    val data = new Array[Byte](file.length().asInstanceOf[Int])
    val io = new FileInputStream(file)
    io.read(data)
    io.close()
    Ok(data).as("image/jpeg")
  }
  
}
