package io.nexilis.service.data.rooms

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 io.nexilis.service.data.daos.*
import io.nexilis.service.data.entities.*

@Database(
    // Declare all Entity here..
    entities = [
        Buddy::class,
        CallCenterHistory::class,
        DiscussionForum::class,
        Follow::class,
        Form::class,
        FormItem::class,
        Group::class,
        GroupMember::class,
        Inquiry::class,
        LinkPreview::class,
        Message::class,
        MessageFavorite::class,
        MessageStatus::class,
        MessageSummary::class,
        Outgoing::class,
        Prefs::class,
        Pull::class,
        ServiceBank::class,
        WorkingArea::class
    ], version = 1, exportSchema = false
)
abstract class ApiRoomDatabase : RoomDatabase() {

    // Declare all Dao here..
    abstract fun buddyDao(): BuddyDao
    abstract fun callCenterHistoryDao(): CallCenterHistoryDao
    abstract fun discussionForumDao(): DiscussionForumDao
    abstract fun followDao(): FollowDao
    abstract fun formDao(): FormDao
    abstract fun formItemDao(): FormItemDao
    abstract fun groupDao(): GroupDao
    abstract fun groupMemberDao(): GroupMemberDao
    abstract fun inquiryDao(): InquiryDao
    abstract fun linkPreviewDao(): LinkPreviewDao
    abstract fun messageDao(): MessageDao
    abstract fun messageStatusDao(): MessageStatusDao
    abstract fun messageSummaryDao(): MessageSummaryDao
    abstract fun outgoingDao(): OutgoingDao
    abstract fun prefsDao(): PrefsDao
    abstract fun pullDao(): PullDao
    abstract fun serviceBankDao(): ServiceBankDao
    abstract fun workingAreaDao(): WorkingAreaDao

    class ApiDatabaseCallback : Callback() {

        override fun onCreate(db: SupportSQLiteDatabase) {
            super.onCreate(db)
        }

    }

    companion object {

        @Volatile
        private var INSTANCE: ApiRoomDatabase? = null

        fun getDatabase(context: Context): ApiRoomDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    ApiRoomDatabase::class.java,
                    "main"
                )
                    .addCallback(ApiDatabaseCallback())
                    .addMigrations(migration_1_to_2)
                    .build()
                INSTANCE = instance
                instance
            }
        }

        private val migration_1_to_2 = object : Migration(1, 2) {
            override fun migrate(db: SupportSQLiteDatabase) {
                db.execSQL("ALTER TABLE `Group` ADD COLUMN `be` TEXT NOT NULL")
            }
        }

    }
}