import play.api.GlobalSettings
import play.api.Application
import play.api.db.DB
import play.api.mvc._
import play.api._
import play.api.mvc.Results._
import org.squeryl.Session
import org.squeryl.SessionFactory
import org.squeryl.adapters.MySQLInnoDBAdapter
import org.squeryl.internals.DatabaseAdapter
import org.squeryl.PrimitiveTypeMode._
import models._
object Global extends GlobalSettings{
  private val logger = Logger(getClass())
  override def onStart(app:Application) {
    SessionFactory.concreteFactory = app.configuration.getString("db.default.driver") match {
      case Some("com.mysql.jdbc.Driver") => Some(() => getSession(new MySQLInnoDBAdapter, app))
      case _ => sys.error("Database driver must be either com.mysql.jdbc.driver")
    }
    transaction {
//     PartsListDb.drop
//     PartsListDb.create
    }
  }
  // 500 - internal server error
  override def onError(request: RequestHeader, ex: Throwable) = {
    logger.error("this is Error")
    InternalServerError(views.html.errors.error500Page(ex))
  }
  // called when a route is found, but it was not possible to bind the request parameters
  override def onBadRequest(request: RequestHeader, error: String) = {
    BadRequest("Bad Request: " + error)
  }
  // 404 - page not found error
  override def onHandlerNotFound(request: RequestHeader):Result = {
    NotFound(views.html.errors.onHandlerNotFound(request))
  }
  
  def getSession(adapter: DatabaseAdapter, app: Application) = Session.create(DB.getConnection()(app), adapter)

}
