99 lines
2.8 KiB
Kotlin
99 lines
2.8 KiB
Kotlin
package com.power.ops.vms
|
|
|
|
import android.app.Application
|
|
import android.content.Context
|
|
import androidx.compose.runtime.rememberCoroutineScope
|
|
import androidx.compose.ui.platform.LocalContext
|
|
import androidx.lifecycle.AndroidViewModel
|
|
import androidx.lifecycle.viewModelScope
|
|
import androidx.room.Dao
|
|
import androidx.room.Database
|
|
import androidx.room.Entity
|
|
import androidx.room.Insert
|
|
import androidx.room.OnConflictStrategy
|
|
import androidx.room.PrimaryKey
|
|
import androidx.room.Query
|
|
import androidx.room.Room
|
|
import androidx.room.RoomDatabase
|
|
import androidx.room.Update
|
|
import com.power.ops.managers.FileManager
|
|
import com.power.ops.managers.LogManager
|
|
import kotlinx.coroutines.flow.Flow
|
|
import kotlinx.coroutines.flow.collect
|
|
import kotlinx.coroutines.flow.filterNotNull
|
|
import kotlinx.coroutines.flow.first
|
|
import kotlinx.coroutines.flow.map
|
|
import kotlinx.coroutines.launch
|
|
|
|
|
|
@Entity(tableName = "settings")
|
|
data class SettingEntity(
|
|
@PrimaryKey(autoGenerate = true) val id: Int = 0,
|
|
var key: String,
|
|
var value: String
|
|
)
|
|
|
|
@Dao
|
|
interface SettingDao {
|
|
@Query("select * from settings")
|
|
fun querySettings(): Flow<List<SettingEntity>>
|
|
|
|
@Insert(onConflict = OnConflictStrategy.IGNORE)
|
|
suspend fun createSetting(setting: SettingEntity)
|
|
|
|
@Update
|
|
suspend fun updateSetting(setting: SettingEntity)
|
|
}
|
|
|
|
@Database(entities = [SettingEntity::class], version = 1)
|
|
abstract class SettingDatabase : RoomDatabase() {
|
|
abstract fun settingDao(): SettingDao
|
|
companion object {
|
|
@Volatile
|
|
private var INSTANCE: SettingDatabase? = null
|
|
fun getDatabase(context: Context): SettingDatabase {
|
|
return INSTANCE ?: synchronized(this) {
|
|
val instance = Room.databaseBuilder(
|
|
context.applicationContext,
|
|
SettingDatabase::class.java,
|
|
"setting"
|
|
).build()
|
|
INSTANCE = instance
|
|
instance
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
class SettingVM {
|
|
lateinit var dao: SettingDao
|
|
lateinit var settings:Flow<List<SettingEntity>>
|
|
suspend fun getSetting(key: String): SettingEntity? {
|
|
settings = dao.querySettings()
|
|
val res = settings.map {
|
|
it.find { setting ->
|
|
setting.key == key
|
|
}
|
|
}.first()
|
|
return res
|
|
}
|
|
|
|
suspend fun setSetting(key: String, value: String) {
|
|
val res = getSetting(key)
|
|
if (res == null) {
|
|
dao.createSetting(SettingEntity(key = key, value = value))
|
|
} else {
|
|
res.value = value
|
|
dao.updateSetting(res)
|
|
}
|
|
}
|
|
|
|
fun initDao(context: Context) {
|
|
dao = SettingDatabase.getDatabase(context).settingDao()
|
|
settings = dao.querySettings()
|
|
}
|
|
|
|
companion object {
|
|
val singleton: SettingVM = SettingVM()
|
|
}
|
|
} |