package io.github.sdsstudios.ScoreKeeper.Database

import android.arch.persistence.room.Database
import android.arch.persistence.room.Room
import android.arch.persistence.room.RoomDatabase
import android.arch.persistence.room.TypeConverters
import android.content.Context
import io.github.sdsstudios.ScoreKeeper.Database.Dao.GameDao
import io.github.sdsstudios.ScoreKeeper.Database.Dao.PlayerDao
import io.github.sdsstudios.ScoreKeeper.Database.Dao.ScoresDao
import io.github.sdsstudios.ScoreKeeper.Database.Dao.TimeLimitDao
import io.github.sdsstudios.ScoreKeeper.Database.TypeConverters.DateConverter
import io.github.sdsstudios.ScoreKeeper.Database.TypeConverters.IntListConverter
import io.github.sdsstudios.ScoreKeeper.Game.Game
import io.github.sdsstudios.ScoreKeeper.Game.Player
import io.github.sdsstudios.ScoreKeeper.Game.Scores
import io.github.sdsstudios.ScoreKeeper.TimeLimit

/**
 * Created by sethsch1 on 29/10/17.
 */

/* Database version changelog:
* */

@Database(entities = [(Game::class), (Player::class), (TimeLimit::class), (Scores::class)],
        version = 1)

@TypeConverters(
        DateConverter::class,
        IntListConverter::class
)
abstract class AppDatabase : RoomDatabase() {
    companion object {
        private const val DATABASE_NAME = "scorekeeper_db"
        private var INSTANCE: AppDatabase? = null

        fun getDatabase(context: Context): AppDatabase {
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(context.applicationContext,
                        AppDatabase::class.java,
                        DATABASE_NAME)
                        .build()
            }

            return INSTANCE!!
        }
//
//        private val MIGRATION_1_2 = object : Migration(1, 2) {
//            override fun migrate(database: SupportSQLiteDatabase) {
//                dropColumn(database, GameDao.TABLE_NAME, GameDao.KEY_USE_PLAYER_COLORS)
//            }
//        }
//
//        private fun dropColumn(db: SupportSQLiteDatabase,
//                               tableName: String,
//                               columnToDrop: String) {
//
//            val allColumnsCursor = db.query("SELECT * FROM $tableName")
//
//            val columnNames = allColumnsCursor.columnNames.toMutableList()
//            columnNames.remove(columnToDrop)
//
//            val columnTypes = buildSequence {
//                for (i in 1..columnNames.size){
//                    yield(allColumnsCursor.getType(i))
//                }
//            }.toList()
//
//            Log.e(this::class.java.simpleName, columnTypes.toString())
//
//            val columnsString = columnNames.toString().removePrefix("[").removeSuffix("]")
//
//            db.execSQL("CREATE TABLE $tableName (${columnNames})")
//        }
    }

    abstract fun timeLimitDao(): TimeLimitDao
    abstract fun gameDao(): GameDao
    abstract fun scoresDao(): ScoresDao
    abstract fun playerDao(): PlayerDao
}