package com.ypsx.yppos.room.database

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.ypsx.yppos.room.dao.*
import com.ypsx.yppos.room.entity.*

const val name: String = "yp_pos.db"

@Database(
    entities = [PosConfig::class, PosProduct::class,
        PosBuy::class, PosBuyPart::class, PosBuyPayment::class], version = 3, exportSchema = false
)
abstract class PosDatabase : RoomDatabase() {

    abstract fun posConfigDao(): PosConfigDao
    abstract fun posProductDao(): PosProductDao

    abstract fun posBuyDao(): PosBuyDao
    abstract fun posBuyPaymentDao(): PosBuyPaymentDao
    abstract fun posBuyPartDao(): PosBuyPartDao


    companion object {
        @Volatile
        private var INSTANCE: PosDatabase? = null


        fun getDatabase(context: Context): PosDatabase {
            val tempInstance = INSTANCE
            if (tempInstance != null) {
                return tempInstance
            }

            synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    PosDatabase::class.java,
                    name
                ).allowMainThreadQueries()
                    .addMigrations(MIGRATION_1_2,MIGRATION_2_3)
                    .build()
                INSTANCE = instance
                return instance
            }
        }

        fun clearAllTables() {
            INSTANCE?.clearAllTables()
        }

        var MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE POS_Buy ADD COLUMN `userCouponCode` TEXT;")
                database.execSQL("ALTER TABLE POS_Buy ADD COLUMN `userCouponFee` REAL;")
            }
        }

        var MIGRATION_2_3 = object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE POS_Buy ADD COLUMN `memberPoint` TEXT;")
                database.execSQL("ALTER TABLE POS_BuyPart ADD COLUMN `memberPrice` REAL NOT NULL default 0;")
                database.execSQL("ALTER TABLE POS_BuyPart ADD COLUMN `priceType` TEXT NOT NULL default '';")
            }
        }

        var MIGRATION_3_4 = object : Migration(3, 4) {
            override fun migrate(database: SupportSQLiteDatabase) {

            }
        }
    }




}