package com.ystore.lib.db

import com.mchange.v2.c3p0.*
import java.sql.Connection
import com.ystore.lib.config.*
import com.ystore.lib.log.*
import com.avaje.ebean.Ebean

object Db {

    fun createDs(cfg:IConfig):ComboPooledDataSource{
        assert(cfg.getString("databaseUrl")!=null)
        assert(cfg.getString("databaseDriver")!=null)

        println(cfg.getString("databaseUrl"))
        println(cfg.getString("databaseDriver"))

        Class.forName(cfg.getString("databaseDriver")!!)

        val ds = ComboPooledDataSource()
        ds.setDriverClass(cfg.getString("databaseDriver"))
        ds.setUser(cfg.getString("username"))
        ds.setPassword(cfg.getString("password"))
        ds.setJdbcUrl(cfg.getString("databaseUrl"))
        return ds
    }

    fun <T> tx(f:()->T):T{
        Ebean.beginTransaction()
        var result:T
        try{
            result = f()
            Ebean.commitTransaction()
            return result
        }catch(e:Exception){
            Ebean.rollbackTransaction()
            throw e
        }finally{
            Ebean.endTransaction()
        }
    }

    fun save(c:Collection<*>){
        Ebean.save(c)
    }

    fun save(c:Any){
        Ebean.save(c)
    }
}

data class Column(val name:String, val clazz:Class<Any>)
class Table {
    private val log = Log.find(javaClass<Table>())
    class object{
        fun inspect(conn:Connection,name:String){
            val stmt = conn.createStatement()!!
            val rs = stmt.executeQuery("select * from ${name} where 1=2")
            val tablemeta = rs.getMetaData()
            for (i in 1..tablemeta.getColumnCount()) {
                print("${tablemeta.getTableName(i)}.${tablemeta.getColumnName(i)}:${tablemeta.getColumnClassName(i)}")
                println(" ${tablemeta.getColumnTypeName(i)}(${tablemeta.getPrecision(i)},${tablemeta.getScale(i)})")

            }
        }
    }
    fun t(){
        log.debug("table")
    }
}
/*
fun main(args:Array<String>){
    println("hi")
    val cfg = Config.getDefault()
    //val cfg = Config.getDefault()
    val conn = Db.createDs(cfg.sub("db.visitor")).getConnection()!!
    val dbmeta = conn.getMetaData()!!
    println( "Db: ${dbmeta.getDatabaseProductName()}, Version: ${dbmeta.getDatabaseProductVersion()}  ")

    Table.inspect(conn,"login_user")
//
//    val stmt = conn.createStatement()!!
//    val rs = stmt.executeQuery("select * from login_user where 1=2")!!
//    val tablemeta = rs.getMetaData()!!
//    for (i in 1..tablemeta.getColumnCount()) {
//        println("${tablemeta.getTableName(i)}.${tablemeta.getColumnName(i)}:${tablemeta.getColumnClassName(i)}")
//    }

}*/


