81 lines
2.8 KiB
Kotlin
81 lines
2.8 KiB
Kotlin
package com.example.stepdrink.viewmodel
|
|
|
|
import android.app.Application
|
|
import androidx.lifecycle.AndroidViewModel
|
|
import androidx.lifecycle.viewModelScope
|
|
import com.example.stepdrink.data.local.PreferencesManager
|
|
import com.example.stepdrink.data.local.database.AppDatabase
|
|
import com.example.stepdrink.data.local.entity.WaterRecord
|
|
import com.example.stepdrink.data.repository.WaterRepository
|
|
import com.example.stepdrink.util.DateUtils
|
|
import kotlinx.coroutines.flow.*
|
|
import kotlinx.coroutines.launch
|
|
|
|
// Data class untuk preset containers
|
|
data class WaterContainer(
|
|
val emoji: String,
|
|
val name: String,
|
|
val amount: Int,
|
|
val color: Long = 0xFF2196F3
|
|
)
|
|
|
|
class WaterViewModel(application: Application) : AndroidViewModel(application) {
|
|
|
|
private val repository: WaterRepository
|
|
private val preferencesManager = PreferencesManager(application)
|
|
|
|
val dailyGoal: StateFlow<Int> = preferencesManager.waterGoal
|
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 2000)
|
|
|
|
val todayWaterRecords: StateFlow<List<WaterRecord>>
|
|
val todayTotalWater: StateFlow<Int>
|
|
|
|
// SIMPLE CONTAINERS - Kategori yang clear & sederhana
|
|
val presetContainers = listOf(
|
|
WaterContainer("🥛", "Gelas Kecil", 200, 0xFF64B5F6), // Small glass
|
|
WaterContainer("💧", "Gelas Sedang", 250, 0xFF42A5F5), // Medium glass (STANDARD)
|
|
WaterContainer("🌊", "Gelas Besar", 350, 0xFF2196F3), // Large glass
|
|
WaterContainer("🚰", "Botol Aqua", 600, 0xFF1976D2), // Aqua bottle (MOST COMMON)
|
|
WaterContainer("🫗", "Tumbler", 500, 0xFF1565C0), // Tumbler
|
|
)
|
|
|
|
init {
|
|
val database = AppDatabase.getDatabase(application)
|
|
repository = WaterRepository(database.waterDao())
|
|
|
|
todayWaterRecords = repository.getWaterByDate(DateUtils.getCurrentDate())
|
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
|
|
|
todayTotalWater = todayWaterRecords.map { records ->
|
|
records.sumOf { it.amount }
|
|
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 0)
|
|
}
|
|
|
|
fun addWater(amount: Int) {
|
|
viewModelScope.launch {
|
|
repository.insertWater(DateUtils.getCurrentDate(), amount)
|
|
}
|
|
}
|
|
|
|
fun addWaterFromContainer(container: WaterContainer) {
|
|
addWater(container.amount)
|
|
}
|
|
|
|
fun deleteWater(record: WaterRecord) {
|
|
viewModelScope.launch {
|
|
repository.deleteWater(record)
|
|
}
|
|
}
|
|
|
|
fun getProgressPercentage(): Float {
|
|
return (todayTotalWater.value.toFloat() / dailyGoal.value.toFloat()).coerceIn(0f, 1f)
|
|
}
|
|
|
|
fun getLastDrinkTime(): Long? {
|
|
return todayWaterRecords.value.maxByOrNull { it.timestamp }?.timestamp
|
|
}
|
|
|
|
fun getContainerByAmount(amount: Int): WaterContainer? {
|
|
return presetContainers.find { it.amount == amount }
|
|
}
|
|
} |