package fr.iut.ouafff.data.persistance

import android.app.Application
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import fr.iut.ouafff.DogApplication
import fr.iut.ouafff.data.Dog
import fr.iut.ouafff.data.persistance.converter.DateToLongConverter
import fr.iut.ouafff.data.persistance.converter.GenderToIntConverter

private const val DOG_DB_FILENAME = "dogs.db"

@Database(entities = [Dog::class], version = 1)
@TypeConverters(GenderToIntConverter::class, DateToLongConverter::class)
abstract class DogDatabase : RoomDatabase() {

    abstract fun dogDAO(): DogDao

    companion object {
        private lateinit var application: Application

        @Volatile
        private var instance: DogDatabase? = null

        fun getInstance(): DogDatabase {
            if (::application.isInitialized) {
                if (instance == null)
                    synchronized(this) {
                        if (instance == null)
                            instance = Room.databaseBuilder(
                                application.applicationContext,
                                DogDatabase::class.java,
                                DOG_DB_FILENAME
                            )
                                .build()
                    }
                return instance!!
            } else
                throw RuntimeException("the database must be first initialized")
        }


        @Synchronized
        fun initialize(app: DogApplication) {
            if (::application.isInitialized)
                throw RuntimeException("the database must not be initialized twice")

            application = app
        }
    }
}
