package de.ladkau.deckinadash.ui.config

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import de.ladkau.deckinadash.data.ConfigRepository
import de.ladkau.deckinadash.data.DeckConfig
import de.ladkau.deckinadash.notify.NotificationScheduler
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

class ConfigViewModel(application: Application) : AndroidViewModel(application) {
    private val configRepository = ConfigRepository(application)

    // A local editable draft, seeded once from the persisted config below -
    // deliberately not a live collection of configRepository.config, so
    // in-progress edits aren't clobbered by DataStore's own emission of the
    // write this same screen is about to make on save().
    private val _config = MutableStateFlow(DeckConfig())
    val config: StateFlow<DeckConfig> = _config.asStateFlow()

    init {
        viewModelScope.launch {
            _config.value = configRepository.config.first()
        }
    }

    fun update(transform: (DeckConfig) -> DeckConfig) {
        _config.value = transform(_config.value)
    }

    /** Persists the current draft and reschedules the daily notification -
     * the other of NotificationScheduler.reschedule()'s two required call
     * sites (see its own doc comment; the first is app launch). */
    fun save(onSaved: () -> Unit) {
        viewModelScope.launch {
            val toSave = _config.value.copy(configured = true)
            configRepository.save(toSave)
            NotificationScheduler.reschedule(getApplication(), toSave)
            onSaved()
        }
    }
}
